搜索

首页  >  问答  >  正文

javascript - typescript关于接口,对象字面量额外属性检测问题,为什么使用断言或者变量时就不会检测额外属性?

interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare(config: SquareConfig): { color: string; area: number } {
    // ...
}

let mySquare = createSquare({ colour: "red", width: 100 });

ts编译这段代码时会抛错,但是使用如下两种方式就不会抛错,这是什么原理?官网的解释让我无法理解,只会让我觉得ts语法好随便...

let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);

或者

let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);

这样都不会报错,使用断言的时候(as/<>)是会按照什么规则比照接口吗?然后将对象字面量复制给变量,我知道这是对象的一个引用指针,但是这样为什么就不会检测额外的属性了呢?官网地址

習慣沉默習慣沉默2799 天前738

全部回复(2)我来回复

  • 为情所困

    为情所困2017-06-30 09:54:24

    第一个例子:as 不是断言吧 as 是强制转化 就说明你知道你要做的事情 当然 ts 也就让你编译过了
    第二个例子 好像本来就应该过的吧 color 你又不是一定要; colour 是另外一个属性了
    以前不过的原因是 ts 对 对象字面量有独特的 check 罢了

    回复
    0
  • PHP中文网

    PHP中文网2017-06-30 09:54:24

    1. as 是强制类型转换,强制把一个变量当作另一种类型使用,运行时出问题你自己负责。

    2. 使用对象字面量赋值对象的检测逻辑和使用变量赋值对象的机制不一样。

    interface SquareConfig {
        color?: string;
        width?: number;
    }
    
    function test(config: SquareConfig): void {}
    
    let a = { colour: "red", width: 100 };
    // 不报错, typeof a 与 SquareConfig 类型兼容
    let b: SquareConfig = a; 
    
    // 报错,声明 c 是 SquareConfig 类型但是给了不存在的属性
    let c: SquareConfig = { colour: "red", width: 100 }; 
    
    // 报错,原因和上面类似
    test({ colour: "red", width: 100 })
    
    // 不报错,强制把这个对象字面量当 SquareConfig 类型使用,出问题你自己背锅
    let d: SquareConfig = <SquareConfig> { colour: "red", width: 100 };

    回复
    0
  • 取消回复