转换为接口的TypeScript对象不应该编译?

时间:2018-06-06 01:58:40

标签: typescript

我无法理解为什么要编译这个TypeScript代码(TypeScript 2.8.3所有严格检查)

我投了一个对象来输入IUser并包含一个不存在的属性" bob"

我已阅读有关超额支票的文件 - https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks

但是,如果我将其编译,那么它仍然没有意义。 - / p>

最终的问题是:我如何才能真正在这个对象上进行正确的输入 - 这样将它转换为具有非接口成员的对象(可能/可能是拼写错误)应该无法编译。

interface IUser {
    name: string
}

const func = (user: IUser) => {
    alert(user)
}

func(<IUser> {
    name: "bob",
    bob: true
} as IUser)

1 个答案:

答案 0 :(得分:3)

仅在将对象文字指定给变量或函数参数时才执行额外属性检查。添加任何类型的强制转换都会禁用该检查,因为该值实际上可分配给该类型。此功能称为Strict object literal assignment checking

  

在对象文字中指定属性是错误的   在分配给变量或时,未在目标类型上指定   传递给非空目标类型的参数。

额外属性给出错误的示例:

interface IUser {
  name: string
}

const anotherFunc = function (u: IUser) {
    // whatever
}

const func = function() {
    anotherFunc({
        name: "bob",
        bob: true
    })
}

// Argument of type '{ name: string; bob: boolean; }' is not assignable to parameter of type 'IUser'.
//   Object literal may only specify known properties, and 'bob' does not exist in type 'IUser'.