声明联合类型的例子:

type Fruit = 'apple' | 'banana' | 'orange';
type Color = 'red' | 'green' | 'blue';

function getFruitColor(fruit: Fruit): Color {
  if (fruit === 'apple') {
    return 'red';
  } else if (fruit === 'banana') {
    return 'yellow';
  } else {
    return 'orange';
  }
}

const fruitColor: Color = getFruitColor('apple');  // 此处 fruitColor 的类型为 Color,可以是 'red'、'green' 或 'blue'

声明交叉类型的例子:

type Person = {
  name: string;
  age: number;
};

type Employee = {
  company: string;
  position: string;
};

type EmployeeWithPerson = Employee & Person;

const employee: EmployeeWithPerson = {
  name: 'John',
  age: 30,
  company: 'ABC Inc.',
  position: 'Manager',
};

在上述例子中,EmployeeWithPersonEmployeePerson 的交叉类型,表示同时具有 EmployeePerson 的属性。employee 变量的类型被声明为 EmployeeWithPerson,可以访问 nameagecompanyposition 属性

举例type可以用于声明联合类型和交叉类型代码

原文地址: https://www.cveoy.top/t/topic/iIij 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录