什么是泛型可以理解为动态的类型,类型中可以接受参数。我们要做一个输入什么就返回什么的函数,当我们将类型写死后,传递其他类型的数据就会在编译时报错类型错误。我们能不能做到在传递参数时声明一个类型,让我们声明的类型进行判断呢?ts自动换行复制function returnSomething(inputSomething: string): string { return inputSomething } returnSomething<string>("wx") returnSomething(23) // 报错 这时我们可以使用泛型接受类型参数ts自动换行复制function returnSomething<T>(inputSomething: T): T { return inputSomething } returnSomething<string>("wx") returnSomething<number>(2) 泛型的继承 extends有时我们需要一些特定类型的参数,里面包含一些相同的类型,我们可以用 extends 继承来约束可以传递的参数ts自动换行复制function getLength<T extends { length: number }>(arg: T): number { return arg.length } function getLength<T extends { length: number }>(arg: T): number { return arg.length } getLength("www") getLength([2, 3, 4]) getLength(2) // 报错 类中使用我们可以使用泛型对函数的类型做限制,将类型的定义部分开放给用户。ts自动换行复制class User<T> { constructor(private user: T) {} get(): T { return this.user } } interface IUser { name: string age: number } const user = new User<IUser>({ age: 2, name: "xxx" }) console.log(user.get()) interface 使用泛型ts自动换行复制interface IArticle<B, C> { title: string isLock: B comments: C[] } interface CommentType { content: string } const article: IArticle<boolean, CommentType> = { title: "测试文章", isLock: false, comments: [{ content: "测试评论" }], }
评论区
评论加载中...