TypeScript项目中常见的类型定义

72 阅读1分钟

1.根据一个字段的类型,限定另一个字段的类型

在ts中一个对象有type和value属性,type可能为字符串'car'或者'money',当type为'car'时,value属性为string类型,当type为'money'时,value为number类型,怎么定义这个对象类型?

// 方案一:使用联合类型
type MyObject =
  | {
      type: 'car'
      value: string
    }
  | {
      type: 'money'
      value: number
    }

const car: MyObject = {
  type: 'car',
  value: 'Tesla' // ✅ 正确
}

const money: MyObject = {
  type: 'money',
  value: 100 // ✅ 正确
}

// 方案二:泛型+类型映射
type ValueType<T extends 'car'|'money'> = T extends 'car' ? string : number;
type MyObject<T extends 'car'|'money'> = {
    type: T;
    value: ValueType<T>;
}
const money: MyObjectt<'car'> = {
  type: 'money',
  value: 100 // ✅ 正确
}

2.变量的类型为枚举类型的值

enum DataSourceType {
  DICT = 'dict', // 数据字典
  ATTR = 'attr', // 产品数据
  REMOTE = 'remote', // 自定义接口
  STATIC = 'static', // 自定义静态数据
}
// 如果定义变量type类型是枚举类型的值:'dict'|'attr'|'remote'|'static'
const type:`${DataSourceType}` = 'dict' 
// 用`${DataSourceType}` 这种方式定义type的类型

3.定义input事件

<input type="text" :value="username" @input="username = (<HTMLInputElement>$event.target).value">