【发布时间】:2020-01-17 05:06:41
【问题描述】:
为什么可以分配hoge2和hoge3却不能分配给hoge1?
const hoge1: { foo: string }[] = [{ foo: 'test', extraVal: 1 }]; // compile error
// Type '{ foo: string; extraVal: number; }' is not assignable to type '{ foo: string; }'.
// Object literal may only specify known properties, and 'extraVal' does not exist in type '{ foo: string; }'. TS2322
const val = [{ foo: 'test', extraVal: 1 }];
const hoge2: { foo: string }[] = val; // ok
const hoge3: { foo: string }[] = (() => [{ foo: 'test', extraVal: 1 }])(); // ok
【问题讨论】:
-
你也可以看看here
-
您可能想阅读来自@ford04 的链接。简而言之,对象字面量
[{ foo: 'test', extraVal: 1 }]在打字稿中得到特殊处理。您有责任提供正确的类型,以免导致过多的属性检查。但是对象变量可能来自api等,所以它会偷偷检查。这是一个设计决定。
标签: typescript