Home > Software engineering >  Typescript: T extends string | number = string?
Typescript: T extends string | number = string?

Time:12-04

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

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

CodePudding user response:

= 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.

  • Related