浅学TypeScript(8)——泛型
函数泛型
- 参数泛型
// 函数泛型
function testGenerics<T>(v: T) {
console.log(v);
}
// 手动设置类型
testGenerics<string>("123");
// 自动识别类型
testGenerics(123);
- 返回值泛型
function testGenerics2<T>(v: T | T[]): T[] {
if (v instanceof Array) {
return v;
}
else {
return [v];
}
}
console.log(testGenerics2<string>("123"));
console.log(testGenerics2([1, 2, 3]));
- 函数泛型类型
// 函数泛型类型
let aFunc: <T>(string, T) => void;
aFunc = function<T> (s:string, v:T) {
console.log(s, v);
};
- 泛型函数接口
// 泛型函数接口
interface InterfaceG<T> {
(v1:string, v2:T) :T;
}
let interfaceG: InterfaceG<string> = function(v1:string, v2:string) : string {
console.log(v1, v2);
return v2;
};
interfaceG("123", "233");
接口泛型
// 泛型接口
interface IG<T> {
valueOf(t: T): void;
toString(): string;
}
class ClassIG implements IG<string> {
private t: string;
valueOf(t: string): void {
this.t = t;
}
toString(): string {
return this.t;
}
}
let classIG = new ClassIG();
classIG.valueOf("123");
console.log(classIG.toString());
类泛型
// 类泛型
class ClassG<T> {
print(v: T): void {
console.log(v);
}
}
let classG = new ClassG<string>();
classG.print("233");
// Error:(13, 14) TS2345: Argument of type '233' is not assignable to parameter of type 'string'.
// classG.print(233);
类型泛型
和泛型函数有一些相似,基于类型合并应该可以实现更加复杂的类型。
// 泛型 type
type gt<T> = (string, T) => string;
let funcxt:gt<string> = function f(s1: string, s2:string) {
return s1 + s2;
};
泛型约束
- 继承约束
// 泛型约束
// 基础抽象
class BaseEntity<ID> {}
class BaseDao<T extends BaseEntity<ID>, ID> {}
class BaseService<D extends BaseDao<T, ID>, T extends BaseEntity<ID>, ID> {}
class BaseController<S extends BaseService<D, T, ID>, D extends BaseDao<T, ID>, T extends BaseEntity<ID>, ID> {}
// 书的实体、dao、service、controller
class Book extends BaseEntity<number>{}
class BookDao extends BaseDao<Book, number> {}
class BookService extends BaseService<BookDao, Book, number> {}
class BookController extends BaseController<BookService, BookDao, Book, number> {}
- keyof 约束
约束K只能是T的某一个键
// keyof
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a"); // okay
// getProperty(x, "m"); // error: Argument of type 'm' isn't assignable to 'a' | 'b' | 'c' | 'd'.
感叹:
为了类型检查牺牲了js的灵活性
版权声明
本文章由作者“衡于墨”创作,转载请注明出处,未经允许禁止用于商业用途
发布时间:2019年12月05日 21:49:04
备案号:
闽ICP备19015193号-1
关闭特效
评论区#
还没有评论哦,期待您的评论!
引用发言