typescript 关于 接口额外属性的检查问题


interface sq {
    width?: string;
    label?: string;
}

function cs(config: sq) {
    // ...
}
// 调用cs函数 方式一
let oov = { color: "red", label: 'la' }
let myS1 = cs(oov);


// 调用cs函数 方式二
let myS2 = cs({ color: "red", label: 'la' });
// 方式二提示 报错
// 类型“{ color: string; label: string; }”的参数不能赋给类型“sq”的参数。
//对象文字可以只指定已知属性,并且“color”不在类型“sq”中。

这个是为啥?~~~~

阅读 1.6k
1 个回答

TS 的特性,故意这样设计的,叫 Excess Property Checks(额外属性检查)。

目的就是尽量避免隐式的 any 的出现,除非你显式地指定:

interface sq {
    width?: string;
    label?: string;
    [key: string]: any;
}

或者编译选项里 --suppressImplicitAnyIndexErrors 手动指定为 false

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进