为什么TypeScript在强制转换时不抱怨属性不包含在状态中?

8hhllhi2  于 6个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(66)

为什么TypeScript的行为方式在我的情况下?
如果我直接输入一个对象,它会抱怨没有在接口中定义的属性,但是如果我转换对象,它允许添加任何没有在接口中定义的随机属性。
最好用一个例子来解释:

interface House {
  windows: number;
  garden: boolean;
}

const house1: House = {
  windows: 5,
  garden: true,
  garage: true // not allowed
};

const whatever = {
  house2: <House> {
    windows: 3,
    garden: true,
    garage: true // why is it here allowed?
  }
};

字符串

cfh9epnr

cfh9epnr1#

它的工作原理是因为它是一个类型Assert。基本上告诉编译器它是什么类型,但不保护它,例如。

const house1 = <House> {
  windows: 5,
  garden: true,
  garage: true // allowed
};

字符串
基本上,你告诉ts编译器不要执行特殊的数据检查或重组。
你可以为它输入合适的属性类型,例如。

const whatever: { house2: House } = {
    house2: {
        windows: 3,
        garden: true,
        garage: true // not allowed
    }
};

相关问题