typescript中的type如何使用
在TypeScript中,type关键字用于创建类型别名
。类型别名可以为任何类型提供一个新名字,这有助于使代码更加清晰和可维护
。以下是一些使用type关键字的示例:
基本类型别名
type Age = number;
let myAge: Age = 30;
对象类型别名
type User = {id: number;name: string;
};
let user: User = {id: 1,name: "Alice",
};
联合类型
type Status = 'active' | 'inactive' | 'pending';
let currentStatus: Status = 'active';
元组类型
type Point = [number, number];
let coordinates: Point = [10, 20];
函数类型
type AddFunction = (a: number, b: number) => number;
let add: AddFunction = (a, b) => a + b;
字符串字面量类型
type CardinalDirection = 'North' | 'East' | 'South' | 'West';
let direction: CardinalDirection = 'North';
扩展类型
type BasicUser = {id: number;name: string;
};type ExtendedUser = BasicUser & {email: string;
};let extendedUser: ExtendedUser = {id: 1,name: "Bob",email: "bob@example.com",
};
映射类型
type ReadOnly<T> = {readonly [P in keyof T]: T[P];
};type ReadOnlyUser = ReadOnly<User>;let readOnlyUser: ReadOnlyUser = {id: 1,name: "Charlie",
};// Error: Cannot assign to 'id' because it is a read-only property.
// readOnlyUser.id = 2;
条件类型
type IsString<T> = T extends string ? true : false
type IsStringResult = IsString<string>; // true
type IsNumberResult = IsString<number>; // false
这些只是type关键字在TypeScript中的一些基本用法。类型别名可以极大地提高代码的可读性和可维护性,特别是在处理复杂的类型时。