function firstElement1<Type>(arr: Type[]) { return arr[0]; } function firstElement2<Type extends any[]>(arr: Type) { return arr[0]; } // a: number (good) const a = firstElement1([1, 2, 3]); // b: any (bad) const
In this TypeScript tutorial, we will learn about generic interfaces, classes, and methods and explore their syntax, usage, and benefits. 1. Generic Functions A function may be made generic by placing an alias for a type parameter, wrapped in angle brackets, immediately before the parameters par...
}constclones = cloneArray(heros); When we check the 'clones' type, you can see it is 'any[]'. To add more type information we can change the function: function cloneArray<T>(ary: T[]): T[] {returnary.slice(0); } Now we get 'clones' type as 'HasName[]'. Generic Class: c...
function swap<T, U>(tuple: [T, U]): [U, T]{ return [tuple[1], tuple[0]] } 1. 2. 3. 传入一个参数,定义元组第 0 项为 string 类型,第 1 项为 number 类型。 const arr = swap<string, number>(['abc', 123]) 1. 得到的函数返回值,第 0 项为 number 类型,第 1 项为 string ...
function combine<Type>(arr1: Type[], arr2: Type[]): Type[] { return arr1.concat(arr2); } 编译错误: 解决办法:使用尖括号语法,显式传入类型参数:这里 T = string | number,意思是接收 string 或者 number 类型均可。 编写generic 函数的最佳实践 ...
泛型(Generic) 定义一个函数或类时,有些情况下无法确定其中要使用的具体类型(返回值、参数、属性的类型不能确定); 此时泛型便能够发挥作用; 举个例子: function test(arg: any): any{ return arg; } 1. 2. 3. 上例中,test函数有一个参数类型不确定,但是能确定的时其返回值的类型和参数的类型是相同的;...
泛型函数 (Generic Functions) 我们经常需要写这种函数,即函数的输出类型依赖函数的输入类型,或者两个输入的类型以某种形式相互关联。让我们考虑这样一个函数,它返回数组的第一个元素: function firstElement(arr: any[]) { return arr[0]; } 注意此时函数返回值的类型是 any,如果能返回第一个元素的具体类型就...
type GenericReflectFunction<P> = (param: P) => P;interface IGenericReflectFunction<P> {(param: P): P;}const reflectFn4: GenericReflectFunction<string> = reflect; // 具象化泛型const reflectFn5: IGenericReflectFunction<number> = reflect; // 具象化泛型const reflectFn3Return = reflectFn4('...
# 泛型函数 (Generic Functions)我们经常需要写这种函数,即函数的输出类型依赖函数的输入类型,或者两个输入的类型以某种形式相互关联。让我们考虑这样一个函数,它返回数组的第一个元素:function firstElement(arr: any[]) { return arr[0]; } 注意此时函数返回值的类型是 any,如果能返回第一个元素的具体类型就...
function generic<T>() {} interface Generic<T> {} class Generic<T> {} 代码块 预览 复制 2. 初识泛型 之所以使用泛型,是因为它帮助我们为不同类型的输入,复用相同的代码。比如写一个最简单的函数,这个函数会返回任何传入它的值。如果传入的是 number 类型:function identity(arg: number): number { ...