我遇到了这样的代码块
shape:IPoint={x,y,z} as IPoint;
这是使用as关键字的正确方法吗?
答案 0 :(得分:0)
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