当在声明时给出变量类型时,用作运算符是否多余



>我遇到了这样的
代码块shape:IPoint={x,y,z} as IPoint;
这是用作关键字的正确方法吗?

as是一个类型断言,如果对象 { x, y, z } 符合接口,那么它是多余的。

例如,这里将是多余的:

interface IPoint { x: number, y: number, z: number }
let x = 0, y = 0, z = 0;
let shape:IPoint={x,y,z} ; // no need to assert  

如果对象不符合接口,但我们想强制赋值,那么断言不是多余的(但显式变量类型可以说是多余的(

interface IPoint { x: number, y: number, z: number, w: number }
let x = 0, y = 0, z = 0;
let shape = {x,y,z} as IPoint; // not really a point but we have some reason to pretent it is a IPoint

最新更新