TypeScript 不应该抱怨我分配了错误的类型吗?
Shouldn't TypeScript complain about me assigning a wrong type?
考虑以下代码:(playground here)
interface Foo {
attribute1: string;
attribute2: string;
}
type Bar {
attribute1: string;
}
const values : Foo = { attribute1: "hello", attribute2: "world" }
const values2 : Bar = values;
在编译时可以清楚地识别出 values: Foo
比 values2 : Bar
具有更多的属性。但是我可以分配 const values2 : Bar = values;
。 TypeScript 不应该抱怨这个吗?我对type
的理解有误吗?
这是 Typescript 中的正常行为,编译器会为你做的是在给 values2 赋值时,它会检查变量 values 是否有一个名为 attribute1 的字符串类型的字段,仅此而已,它不会检查值是否有其他字段,我希望我已经为你说清楚了。
您希望 excess property checks 在 TypeScript 中更频繁地出现。
额外的 属性 检查在 TS 中确实存在,但只有在 直接给对象字面量 .
时才会发生
所以在你的例子中,values2
确实没有显示 TS 错误:
type Bar { attribute1: string; }
const values : Foo = { attribute1: "hello", attribute2: "world" }
const values2 : Bar = values;
但是当我直接将 values
对象写为对象文字(用花括号括起来的以逗号分隔的名称-值对列表)时,没有先将其存储在 values
变量中,我确实在添加 attribute2
属性 时收到 TypeScript 错误,我没有在 Bar
类型中明确定义:
type Bar { attribute1: string; }
const values2WithWarning : Bar = { attribute1: "hello", attribute2: "world" };
TS错误:
Type '{ attribute1: string; attribute2: string; }' is not assignable to type 'Bar'.
Object literal may only specify known properties, but 'attribute2' does not exist in type 'Bar'. Did you mean to write 'attribute1'?(2322)
考虑以下代码:(playground here)
interface Foo {
attribute1: string;
attribute2: string;
}
type Bar {
attribute1: string;
}
const values : Foo = { attribute1: "hello", attribute2: "world" }
const values2 : Bar = values;
在编译时可以清楚地识别出 values: Foo
比 values2 : Bar
具有更多的属性。但是我可以分配 const values2 : Bar = values;
。 TypeScript 不应该抱怨这个吗?我对type
的理解有误吗?
这是 Typescript 中的正常行为,编译器会为你做的是在给 values2 赋值时,它会检查变量 values 是否有一个名为 attribute1 的字符串类型的字段,仅此而已,它不会检查值是否有其他字段,我希望我已经为你说清楚了。
您希望 excess property checks 在 TypeScript 中更频繁地出现。
额外的 属性 检查在 TS 中确实存在,但只有在 直接给对象字面量 .
时才会发生所以在你的例子中,values2
确实没有显示 TS 错误:
type Bar { attribute1: string; }
const values : Foo = { attribute1: "hello", attribute2: "world" }
const values2 : Bar = values;
但是当我直接将 values
对象写为对象文字(用花括号括起来的以逗号分隔的名称-值对列表)时,没有先将其存储在 values
变量中,我确实在添加 attribute2
属性 时收到 TypeScript 错误,我没有在 Bar
类型中明确定义:
type Bar { attribute1: string; }
const values2WithWarning : Bar = { attribute1: "hello", attribute2: "world" };
TS错误:
Type '{ attribute1: string; attribute2: string; }' is not assignable to type 'Bar'.
Object literal may only specify known properties, but 'attribute2' does not exist in type 'Bar'. Did you mean to write 'attribute1'?(2322)