唯客微博客

专注于计算机,嵌入式领域的技术

0%

TypeScript学习笔记 - 额外的属性检测

先来看个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
interface Config {
width?: number;
}

function CalculateAreasconfig: Config): { area: number} {
let square = 100;
if (config.width) {
square = config.width * config.width;
}
return square;
}

let mySquare = CalculateAreas({ widdth: 5 });

我们传入的参数是widdth,并不是width

此时TypeScript会认为这段代码可能存在问题。对象字面量当被赋值给变量或作为参数传递的时候,会被特殊对待而且经过“额外属性检查”。

如果一个对象字面量存在任何“目标类型”不包含的属性时,你会得到一个错误。

1
2
// error: 'widdth' not expected in type 'Config'
let mySquare = CalculateAreas({ widdth: 5 });

解决方法,官网上给了三种方式:

第一种使用类型断言:

1
let mySquare = CalculateAreas({ widdth: 5 } as Config);

第二种添加字符串索引签名:

1
2
3
4
interface Config {
width?: number;
[propName: string]: any;
}

这样Config可以有任意数量的属性,并且只要不是width,那么就无所谓他们的类型是什么了。

第三种将字面量赋值给另外一个变量:

1
2
let options = { widdth: 5 };
let mySquare = CalculateAreas(options);
-------------本文结束感谢您的阅读-------------

本文标题:TypeScript学习笔记 - 额外的属性检测

文章作者:Vinx

发布时间:2022年11月04日 - 18:58

最后更新:2023年09月18日 - 11:28

原始链接:https://blog.vinkvin.com/post/34/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。