Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: T extends string | number = string?

How should one understand the following typescript generic declaration?

It’s not clear to me what purpose, additional value, or difference = string adds to the type definition

const match = <T extends string | number = string>(value: T) => {
    console.log("value", value);
}

match(1) // returns 1
match("hi") // returns hi
match("1") // returns "1"

Specifically, what is the difference between these two declarations? To my untrained eye, they both mean T can be a number or string

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

T extends string | number
T extends string | number = string

>Solution :

= string is the default value. If T is unspecified, it defaults to string

In the examples where you showed it being used, typescript can infer what T is from the way it’s being used, so for example, match(1) it’s inferred that T is 1. It won’t use the default of string, even though there was no explicit match<1>(1). So in these particular cases, the default doesn’t end up being that important.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading