过度的类型检查 Excess Property Checks
过度的类型检查,就是ts类型检查会扩大被检查的对象的类型,导致程序过不去类型检查的阶段
注意,ts过不去类型检查不意味着代码不能运行,毕竟最后都是编译为js怎么可能不能运行
例子,上面解释应该看完例子看
interface SquareConfig { |
接上面的:line 14
Argument of type ‘{ colour: string; width: number; }’ is not assignable to parameter of type ‘SquareConfig’. Object literal may only specify known properties, but ‘colour’ does not exist in type ‘SquareConfig’. Did you mean to write ‘color’?
上面的13行接收了一个对象字面量,这个字面量里面有个colour的属性,和函数签名的SquareConfig这个类型的属性color对不上,所以会触发过度类型检查
比如我给你传的就是叫colour的属性, 你ts凭啥认为是我把color写错了呢,这就是过度类型检查
官方的handbook提供了几种小技巧可以避免这种检查
1. 传一个变量进去
let squareOptions = { colour: "red", width: 100 }; |
就是把上面的对象字面量赋给一个变量,再把这个变量给待检查的函数
这样做为啥行呢?
因为ts这时候就会找传进来的这个变量squareOptions和函数签名的共同属性,他俩都有width这个属性,所以放行,能通过函数签名的检查
如果没有公共属性呢,那不好意思,通过不了
let squareOptions = { colour: "red" }; |
Type '{ colour: string; }' has no properties in common with type 'SquareConfig'.Type '{ colour: string; }' has no properties in common with type 'SquareConfig'.
2. 类型断言+索引签名
指定对象字面量的类型的做法
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig); |
对应的SquareConfig类型
interface SquareConfig { |
只要属性名是string类型的就可以,不限制这个属性的名称是color或者width