TypeScript Generics All In One
TypeScript Generics All In One
https://www.typescriptlang.org/docs/handbook/generics.html
https://www.typescriptlang.org/docs/handbook/2/generics.html
泛型 1
Generic Interface
type Log = <T>(value: T) => T;
interface Log {
<T>(value: T):T
}
// 等价的,使用时无需指定类型:
let log: Log = ...
type Log<T> = (value: T) => T;
interface Log<T> {
(value: T):T
}
// 等价的,使用时必须指定类型
let log: Log<number> = ...
泛型 2
Generic Class
demo
Property 'name' has no initializer and is not definitely assigned in the constructor.(2564)
interface Named<T> {
name: string;
value: T; // <-- added
}
class MyNamed<T> implements Named<T> {
name: 'mine';
value: T; // <-- added
}
function findByName<T>(x: Named<T>): T {
// TODO: Implement
return undefined;
}
var x: MyNamed<string>;
var y = findByName(x); // got y: string;
interface Named<T> {
name: string;
value: T; // <-- added
}
class MyNamed<T> implements Named<T> {
// name: 'mine'|undefined;
// name!: 'mine';
// name: 'mine'="mine";
name: string = 'mine';
// value: T;
value!: T; // <-- added
}
function findByName<T>(x: Named<T>): T {
// TODO: Implement
return undefined;
// Type 'undefined' is not assignable to type 'T'.
// 'T' could be instantiated with an arbitrary type which could be unrelated to 'undefined'.(2322)
}
var x: MyNamed<string> = {
name: 'eric',
value: '2022',
};
var y = findByName(x); // got y: string;
https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#generics
blogs
https://ts.chibicode.com/generics
https://alligator.io/typescript/generics-in-typescript/
https://www.tutorialsteacher.com/typescript/typescript-generic-interface
https://www.tutorialsteacher.com/typescript/typescript-generic-class
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/12453976.html
未经授权禁止转载,违者必究!