在TypeScript里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。
(一)简单接口
1、在这里并不能像在其它语言里一样,说传给 printLabel的对象实现了这个接口,我们只会去关注值的外形。
2、类型检查器不会去检查属性的顺序
ts代码:
interface LabelValue {
label: string;
}
function printLabel(labelObj: LabelValue) {
console.log(labelObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
js代码:
function printLabel(labelledObj) {
console.log(labelledObj.label);
}
let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);
(二)接口的可选属性:
1、可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个?符号。
2、可选属性可以对可能存在的属性进行预定义 (好处一)
3、可选属性可以捕获引用了不存在的属性时的错误 (好处二)
interface SquareConfig {
color?: string;
width?: number; //好处一
}
function createSquare(config: SquareConfig): { color: string; area: number } {
let newSquare = {color: "white", area: 100};
if (config.clor) {
//好处二
// Error: Property 'clor' does not exist on type 'SquareConfig'
newSquare.color = config.clor;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: "black"});
js代码:
function createSquare(config) {
let newSquare = { color: "white", area: 100 };
if (config.clor) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({ color: "black" });
(三)接口的只读属性:
1、只能在对象刚刚创建的时候修改其值
2、判断该用readonly还是const的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用 const,若做为属性则使用readonly。
interface Point {
readonly x: number;
readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!
3、TypeScript具有ReadonlyArray<T>类型
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
a = ro; // error!
(四)额外的属性检查
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
// ...
}
let mySquare = createSquare({ colour: "red", width: 100 });
我们可能认为width属性是兼容的,不存在color属性,而且额外的colour属性是无意义的。但TypeScript会认为这段代码可能存在bug。因为对象字面量会被特殊对待而且会经过 额外属性检查
跳过额外检查:
方法一:使用类型断言:
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
方法二:添加带有任意数量的其它属性
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}
方法三:将这个对象赋值给一个另一个变量(因为 squareOptions不会经过额外属性检查)
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);