解决什么问题?
通用类型进行抽象
在面向对象语言中,接口是一个很重要的概念,它是对行为的抽象,而具体如何行动需要由类去实现。
TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。
interface Person {name: string;}function getPersonName (person: Person): void => {console.log(person.name)}function setPersonName (person: Person, name: string): void => {person.name = name;}
使用场景
通常情况, 可以类型推断。
工具: quicktype
可选属性
age?: number;
可索引属性
[index: number]: string;[propName: string]: string
函数类型
(source: string, searchStr: string): boolean;
接口继承
interface Person {name: string}interface Teacher extends Person {teachingAge: number}interface Student extends Person {age: number}interface Driver {name: string;age: number;}const teacher = {name: 'Jack',teachingAge: 10}const student = {name: 'Lee',age: 17}const getUserInfo = (user: Person) => {console.log(user.name);}getUserInfo(teacher);getUserInfo(student);// Jack// Lee
🌰
interface Person {readonly name: string, // 只能读不能写age?: Number, // 属性可有可无[propName: string]: any, // 属性不确定say(): string // 方法, 并标注返回类型}class User implments Person {name = 'Jack',say() {return 'hello'}}
interface VS type VS class VS 抽象类 VS 虚拟类
interface 仅可代表对象
type Person = string;interface Person = {}
接口
interface A {<T>(age: T): void;}type B = <T>(age: T) => number;// 实现let getData1: A = <T>(age: T): void => {console.log(age);}
实现
getData1(23);getData1('hello');getData1<string>('hello');// 23// hello// hellolet getData2: B = <T>(age: T): number => {// return age as unknown as number;return <number>(age as unknown);}console.log(getData2(23));console.log(getData2('hello'));console.log(getData2<string>('hello'));// 23// hello// hello
