【问题标题】:Why isn't it assigned, although Array is covariant? [duplicate]为什么不分配它,尽管 Array 是协变的? [复制]
【发布时间】: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


【解决方案1】:

您正在尝试将 2 个值加载到单个值数组中。

{foo: string }[] = 字符串类型的数组

[{ foo: 'test', extraVal: 1 }] = 2 个值的数组(字符串、整数)

这个错误是有道理的,你不能将两个值加载到一个值中:

// Type '{ foo: string; extraVal: number; }' is not assignable to type '{ foo: string; }'.

解决方案是:

const hoge1: { foo: string, extraVal: number }[] = [{ foo: 'test', extraVal: 1 }];

或者,取决于你想要做什么,可能:

const hoge1: { foo: string }[] = [{ foo: 'test'}, {foo: 'extraVal'}];

注意:hoge3 的工作原理是创建一个带有参数() => { statements } 的函数,这基本上只是另一个字符串,因此它正在将一个字符串添加到一个字符串数组中,这很好。

【讨论】:

  • 感谢您的评论。我的问题是,为什么要给hoge1hoge2hoge3分配相同的值,却只有hoge1没有分配?
  • 用 hoge3 解释更新了答案,它正在创建一个带参数的函数,它只是一个大字符串,然后将其添加到字符串数组中。
猜你喜欢
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 2015-04-16
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
相关资源
最近更新 更多