Typescript为什么要区别对待对象字面量和对象引用?

Typescript为什么要区别对待对象字面量和对象引用?

interface Props {
    a: number
}
let objAB = {
    a: 1,
    b: 2
}
let demo1: Props = {
    a: 1,
    b: 2 // Error
}
let demo2: Props = objAB // Ok
阅读 2.4k
2 个回答
However, TypeScript takes the stance that there’s probably a bug in
this code. Object literals get special treatment and undergo excess
property checking when assigning them to other variables, or passing
them as arguments. If an object literal has any properties that the
“target type” doesn’t have, you’ll get an error:
Source

应该是ts认为let demo2: Props = objAB是把objAB当作Props使用,但是let demo1: Props = {a: 1, b: 2}则是直接实现了一个接口,所以需要严格进行校验吧。
所以这样let demo1: Props = { a: 1, b: 2 } as Props;是可以的。

为了更好地类型检测。

interface FooOptions {
    color?: string;
    size?: string;
    smell?: string;
    shyness?: string;
}

function foo(options: FooOptions) {
    // ...
}

foo({
    size: "small",
    colour: "#FF00FF",
    smell: "moderate"
})

上面的例子中,ts 能推断出你把 color 拼错成了 colour 。如果额外的属性合法的话,ts 就无法为这种潜在的错误给予提示。

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