对象类型
匿名
function greet(person: { name: string; age: number }) {
return "Hello " + person.name;
}
接口
interface Person {
name: string;
age: number;
}
function greet(person: Person) {
return "Hello " + person.name;
}
类型别名
type Person = {
name: string;
age: number;
};
function greet(person: Person) {
return "Hello " + person.name;
}
属性修饰
可选
interface PaintOptions {
shape: Shape;
// 属性可选
xPos?: number;
}
只读
interface SomeType {
readonly prop: string;
}
索引签名
interface StringArray {
[index: number]: string;
}
interface NumberOrStringDictionary {
[index: string]: number | string;
length: number; // ok, length is a number
name: string; // ok, name is a string
}
扩展类型
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}
interface ColorfulCircle extends Colorful, Circle {}
交叉类型
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}
type ColorfulCircle = Colorful & Circle;
泛型对象类型
interface Box<Type> {
contents: Type;
}
type Box<Type> = {
contents: Type;
}
type OrNull<Type> = Type | null;
type OneOrMany<Type> = Type | Type[];
type OneOrManyOrNull<Type> = OrNull<OneOrMany<Type>>;
type OneOrManyOrNull<Type> = OneOrMany<Type> | null
type OneOrManyOrNullStrings = OneOrManyOrNull<string>;
数组类型
interface Array<Type> {
length: number;
pop(): Type | undefined;
push(...items: Type[]): number;
// ...
}
ReadonlyArray
const roArray: ReadonlyArray<string> = ["red", "green", "blue"];
let x: readonly string[] = [];
元组类型
type StringNumberPair = [string, number];
// 可以包含剩余元素
type StringNumberBooleans = [string, number, ...boolean[]];
type StringBooleansNumber = [string, ...boolean[], number];
type BooleansStringNumber = [...boolean[], string, number];
// readonly
type ReadonlyStringNumberPair = readonly [string, number]