标签:inter ber app nan class name const 怎么办 bsp
枚举类型的扩展
例如我们有一个枚举类型,但是我们临时想扩展一个怎么办呢?
type Fruit = ‘Apple‘ | ‘Banana‘; const human: {name: string, age: number, favouriteFruit: Fruit} = { name: ‘张三‘, age: 12, favouriteFruit: ‘Orange‘ // Ts会报错,因为没有这个类型 }
我们会这样处理
type Fruit = ‘Apple‘ | ‘Banana‘; const human: {name: string, age: number, favouriteFruit: Fruit | ‘Orange‘ = { name: ‘张三‘, age: 12, favouriteFruit: ‘Orange‘ // Ts就不会报错了 }
如果type想作为一个Object的key呢?
type Fruit = ‘Apple‘ | ‘Banana‘; const human: { name: string, age: number, needFruit: { [key in Fruit]?: number } } = { name: ‘张三‘, age: 12, needFruit: { Apple: 50, Orange: 100, // Ts会报错,因为没有Organge这个类型 } }
我们会这么处理
type Fruit = ‘Apple‘ | ‘Banana‘; const human: { name: string, age: number, needFruit: { [key in Fruit | ‘Orange‘]?: number } } = { name: ‘张三‘, age: 12, needFruit: { Apple: 50, Orange: 100, // Ts就不会报错了 } }
复合类型的扩展
type Human = { name: string, age: number } const human: Human = { name: ‘张三‘, age: 22, gender: ‘Male‘ // Ts报错,没有gender这个字段 }
这个时候,我们用到interfance
type Human = { name: string, age: number } interface SuperHuman extends Human { gender: string } const human: SuperHuman = { name: ‘张三‘, age: 22, gender: ‘Male‘ // Ts就不报错了 }
标签:inter ber app nan class name const 怎么办 bsp
原文地址:https://www.cnblogs.com/amiezhang/p/12384816.html