2024年6月11日发(作者:)
ts 组合类型写法
ts,即TypeScript ,在其中,可以使用以下方式定义组合类型:
1. 交叉类型(Intersection Types):使用
&
运算符来组合多个类型,创建一个新类型,
该类型具有所有原始类型的属性和方法。
typescript
复制代码
type A = { a: string };
type B = { b: number };
type C = A & B; // C 类型同时具有 a 和 b 属性
const c: C = { a: 'hello', b: 123 };
2. 联合类型(Union Types):使用
|
运算符来表示一个值可以是多种类型之一。
typescript
复制代码
type StringOrNumber = string | number;
const value: StringOrNumber = () > 0.5 ? 'hello' : 123;
3. 类型别名(Type Aliases):使用
type
关键字为复杂类型定义别名,使其更易于理解
和使用。
typescript
复制代码
type Person = { name: string; age: number; };
type People = Person[];
const people: People = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
];
4. 元组类型(Tuple Types):用于表示一个已知元素数量和类型的数组。
typescript
复制代码
type StringNumberPair = [string, number];
const pair: StringNumberPair = ['hello', 123];
5. 字面量类型(Literal Types):用于限制变量的值只能是某个具体的字面量值。
typescript
复制代码
type Easing = 'ease-in' | 'ease-out' | 'ease-in-out';
const easing: Easing = 'ease-in';
6. 映射类型(Mapped Types):用于在一个现有类型的基础上创建一个新类型,并可
以对原有类型的每个属性进行修改。
typescript
复制代码
type Person = { name: string; age: number; };
type ReadonlyPerson = { readonly [P in keyof Person]: Person[P]; };
const person: Person = { name: 'Alice', age: 25 };
const readonlyPerson: ReadonlyPerson = person; // 创建一个只读版
本的 person 对象
= 30; // 报错,因为 readonlyPerson 是只读的
发布评论