interface SquareConfig {
color: string;
width: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
let result = {color: 'black', area: 0};
if (config.color) {
result.color = config.color;
}
if (config.width) {
result.area = config.width * config.width;
}
return result;
}
let object = { color: 'black', width: 100, opacity: 0.5 };
let mySquare = createSquare({ color: 'black', width: 100, opacity: 0.5 } as SquareConfig);
额外的属性检查
当将对象字面量赋值给变量或作为参数传递的时候,对象字面量会被特殊对待而且会经过额外属性检查。
如果一个对象字面量存在任何“目标类型”不包含的属性时,你会得到一个错误。
对象字面量绕开额外类型检查的途径
使用类型断言
let mySquare = createSquare({ color: 'black', width: 100, opacity: 0.5 } as SquareConfig);
最佳的方式是能够添加一个字符串索引签名
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}
这个对象赋值给一个另一个变量,传递对象引用而不直接传递对象字面量
let object = { color: 'black', width: 100, opacity: 0.5 };
let mySquare = createSquare(object);