Typescript为什么要区别对待对象字面量和对象引用?
interface Props {
a: number
}
let objAB = {
a: 1,
b: 2
}
let demo1: Props = {
a: 1,
b: 2 // Error
}
let demo2: Props = objAB // Ok
Typescript为什么要区别对待对象字面量和对象引用?
interface Props {
a: number
}
let objAB = {
a: 1,
b: 2
}
let demo1: Props = {
a: 1,
b: 2 // Error
}
let demo2: Props = objAB // Ok
为了更好地类型检测。
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 就无法为这种潜在的错误给予提示。
应该是ts认为
let demo2: Props = objAB
是把objAB
当作Props
使用,但是let demo1: Props = {a: 1, b: 2}
则是直接实现了一个接口,所以需要严格进行校验吧。所以这样
let demo1: Props = { a: 1, b: 2 } as Props;
是可以的。