interface discount {
(price: number): number;
}
let cost: discount = function (price: number): number {
return price * 0.8;
};
interface User {
name: string
age: number
}
interface User {
sex: string
}
/*
User 接口为 {
name: string
age: number
sex: string
}
*/
- interface通过extends继承实现
// 接口扩展接口
interface PointX {
x: number;
}
interface Point extends PointX {
y: number;
}
- type通过&交叉类型实现
type PointX = {
x: number
}
type Point = PointX & {
y: number
}
- interface 在这种情况下无法替代 type
type FavoriteNumber = number | string
- interface 也没法实现 Utility type
- Utility type 用法:
用泛型给它传入一个其他类型,然后Utility type对这个类型进行某种操作
。例如:
type Person = {
name: string
age: number
}
const xiaoMing: Partial<Person> = {name: 'xiaoming'}
//不报错,partial代表部分类型
const shenMiRen:Omit<Person,'name' | 'age'> = {}
// omit代表删除某个类型,这里的值不能出现 name 和 age 属性了
type NewPerson = Pick<Person, 'name'>
// Pick作用是挑选一个对象里的某些属性,变成一个新的类型
type PersonKeys = keyof Person
// 这里的类型(keyof返回的)是一个联合类型:'name' | 'string'
type Age = Exclude<PersonKeys,'name'>
// 这里的类型只有一个age,Exclude与Omit不同,过滤的是联合类型里的类型
type Partial<T> = {
[P in keyof T]?: T[P]
}
-
Exclude
实现:这里的 T extends U,是针对T类型的遍历,这个T是个联合类型,
遍历这个联合类型,符合U,就never,不符合,就返回出来
type Exclude<T,U> = T extends U ? never : T
type Omit<T,K extends keyof any> = Pick<T,Exclude<keyof T,K>>
网友评论