【问题标题】:TypeScript object cast to interface should not compile?TypeScript 对象转换为接口不应该编译?
【发布时间】:2018-11-15 14:21:31
【问题描述】:

我不明白为什么这个 TypeScript 代码应该编译(TypeScript 2.8.3 所有严格检查)

我已将一个对象转换为 IUser 类型并包含一个不存在的属性“bob”

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

但它仍然没有意义,这应该编译 - 鉴于我正在铸造它。

最终的问题是:我如何才能在这个对象上真正获得正确的类型 - 以便将其转换为具有非接口成员的对象(可能/可能的错字)应该无法编译。

interface IUser {
    name: string
}

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

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

【问题讨论】:

  • 为什么需要类型断言('cast')失败?如果您有一个接受IUser 的函数并且您传递了{ name: "bob", bob: true },它将失败。
  • @cartant 我已经更新了代码,所以函数接收对象类型 IUser,它仍然可以编译
  • 如果没有类型断言,它将失败。使用类型断言,您可以绕过多余的属性检查。
  • 对,我不是强迫它遵守 IUser,而是无意中通过告诉编译器“别担心它是 IUser”来强迫它编译...

标签: typescript


【解决方案1】:

仅在将对象字面量分配给变量或函数参数时才进行额外的属性检查。添加任何类型的强制转换都会禁用检查,因为该值实际上是可分配给该类型的。此功能称为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'.

【讨论】:

猜你喜欢
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 2015-02-23
  • 1970-01-01
相关资源
最近更新 更多