1.标记对象类型
匿名标记
typescript
function greet(person: { name: string; age: number }) {
return "Hello " + person.name;
}
interface标记
typescript
interface Person {
name: string;
age: number;
}
function greet(person: Person) {
return "Hello " + person.name;
}
type标记
typescript
type Person = {
name: string;
age: number;
};
function greet(person: Person) {
return "Hello " + person.name;
}
2.属性修饰符
可选属性
typescript
interface PaintOptions {
shape: Shape;
xPos?: number;
yPos?: number;
}
function paintShape(opts: PaintOptions) {
// ...
}
const shape = getShape();
paintShape({ shape });
paintShape({ shape, xPos: 100 });
paintShape({ shape, yPos: 100 });
paintShape({ shape, xPos: 100, yPos: 100 });
只读属性
typescript
interface SomeType {
readonly prop: string;
}
function doSomething(obj: SomeType) {
// We can read from 'obj.prop'.
console.log(`prop has the value '${obj.prop}'.`);
// But we can't re-assign it.
obj.prop = "hello";
}
索引签名
typescript
interface StringArray {
[index: number]: string;
}
const myArray: StringArray = getStringArray();
const secondItem = myArray[1];
3.多余属性检查
typescript
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
return {
color: config.color || "red",
area: config.width ? config.width * config.width : 20,
};
}
let mySquare = createSquare({ colour: "red", width: 100 });
这个例子无法通过类型检查,因为typescript会检查传入的属性。
绕过检查的方法
- 使用断言
typescript
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
- 使用索引签名
typescript
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}
- 将对象分配给其它变量
typescript
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);
4.扩展对象类型
typescript
interface BasicAddress {
name?: string;
street: string;
city: string;
country: string;
postalCode: string;
}
interface AddressWithUnit extends BasicAddress {
unit: string;
}
typescript
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}
interface ColorfulCircle extends Colorful, Circle {}
const cc: ColorfulCircle = {
color: "red",
radius: 42,
};
typescript
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}
type ColorfulCircle = Colorful & Circle;
5.通用对象
typescript
interface Box<Type> {
contents: Type;
}
let box: Box<string>;
let arr:Array<string>;
// 只读数组
let readonlyArr:ReadonlyArray<string>;
// 元组
type StringNumberPair = [string, number];
// 只读元组
let readonlyTuple:readonly [string,number];
let point = [3,4] as const;