(十三)类型别名与限定值

老怪兽2022年11月29日
  • TypeScript
  • Ts
大约 1 分钟

一、类型别名与限定值

说明

通过类型别名我们可以把一长串的类型别名起一个简短的名字,这样既方便我们编写代买,也方便我们复用

  • 在使用地方写上联合类型
interface Product {
    title: string
    price: number | string
}

let product = {
    title: '牛仔裤',
    price: 90
}
  • 使用 type 关键词来定义联合类型
type Price = number | string

interface Product {
    title: string
    price: Price         // 在这里直接使用 type 定义的联合类型
}

let product = {
    title: '牛仔裤',
    price: "¥100"
}

二、type 的其他用法

说明

我们还可以使用 type 定义某些属性,只允许选择它规定的值,比如说 gender 只能选择男女

  • 限定选择值(直接写在类型后面)
type Price = number | string

interface Product {
    title: string
    price: Price         // 在这里直接使用 type 定义的联合类型
    size: 'S' | 'M' | 'L'   // 只允许写这 4 个值中的一个
}

let product = {
    title: '牛仔裤',
    price: "¥100",
    size: 'S'
}
  • 使用 type 关键词来定义别名(这种也是限定类型,只是这个限定的是固定的值)
type Price = number | string
type Size = 'S' | 'M' | 'L'

interface Product {
    title: string
    price: Price         // 在这里直接使用 type 定义的联合类型
    size: Size           // 只允许写这 4 个值中的一个
}

let product = {
    title: '牛仔裤',
    price: "¥100",
    size: 'S'
}
Loading...