Exploring Different Generics in TypeScript:
When using generics in TypeScript, the type of data you receive can vary based on how you define your functions.
// Example with string generic type
function getResult<T>(...v: T[]) {
return v
}
const str = getResult('str', 'str2') // const str: string[]
// Another example with explicit string generic type
const str = getResult<string>('str' as const, 'str2') // const str: string[]
Different Results with Extending Generics:
// Using generics that extend specific types
function getResultByExtendsString<T extends string>(...v: T[]) {
return v
}
const str2 = getResultByExtendsString('str', 'str2') // const str2: ("str" | "str2")[]
// Extending for number type
function getResultByExtendsNumber<T extends number>(...v: T[]) {
return v
}
const num2 = getResultByExtendsNumber(123, 456) // const num2: (123 | 456)[]
Mixed Type Examples:
Generics can also be used with mixed types to create arrays of different possible data types.
type Types = string | number
function getAllResults<P extends Types, Q extends Types>(p: P, v: Q): (P | Q)[] {
return [p, v]
}
const res = getAllResults('str', 123) // const res: ("str" | 123)[]
Understanding the Behavior:
If you're curious about why this behavior occurs, you can explore more by checking out TypeScript Playground.