地图<>类型不建议联合数组的自动填充。

huangapple go评论62阅读模式
英文:

Map<> type not suggesting autofill for union array

问题

在下面的示例中,为什么在将元素输入空数组时,TypeScript 没有为 "foo" 或 "bar" 提供自动填充建议?

const map: Map<string, ('foo' | 'bar')[]> = new Map([
  ['hello', []],
  ['world', []],
]);

当数组中出现除 foo 或 bar 之外的内容时,它会正确显示错误,这可能是一个 tsconfig 的问题,还是我没有正确输入这个 Map?

英文:

In the example below, why is typescript not giving autofill suggestion for "foo" or "bar" when typing elements into an empty array?

const map: Map&lt;string, (&#39;foo&#39; | &#39;bar&#39;)[]&gt; = new Map([
  [&#39;hello&#39;, []],
  [&#39;world&#39;, []],
]);

It is correctly showing error when something other than foo or bar is in the array but no suggestion, could this be a tsconfig problem or am i typing this Map incorrectly?

答案1

得分: 1

你正在将你的 Map 存储到一个带有类型的 map 中,但首先你创建了一个泛型 map。如果你想在创建这个 map 时具有类型,请相应地设置类型,如下所示:

const map: Map<string, ('foo' | 'bar')[]> = new Map<string, ('foo' | 'bar')[]>([
  ['hello', []],
  ['world', []],
]);
英文:

You are storing your Map to a typed map, but you are first of all creating a generic map. If you want to have typings when creating this map, you should also set the types to it accordingly like:

const map: Map&lt;string, (&#39;foo&#39; | &#39;bar&#39;)[]&gt; = new Map&lt;string, (&#39;foo&#39; | &#39;bar&#39;)[]&gt;([
  [&#39;hello&#39;, []],
  [&#39;world&#39;, []],
]);

答案2

得分: 1

你需要用泛型来初始化你的 Map
new Map<string, ('foo' | 'bar')[]>()

你所做的是给你的 map 变量指定了一个显式类型。使用 Map 的泛型构造函数,类型将会自动地正确推断,这意味着你不再需要显式类型了。

const map = new Map<string, ('foo' | 'bar')[]>([
  ['hello', []],
  ['world', []],
]);
英文:

You'll have to initialize your Map with a generic:
new Map&lt;string, (&#39;foo&#39; | &#39;bar&#39;)[]&gt;().

What you did was giving your map variable an explicit type. Use the generic constructor of Map and the type will be infered correctly automatically which means you won't need your explicit type anymore.

const map = new Map&lt;string, (&#39;foo&#39; | &#39;bar&#39;)[]&gt;([
  [&#39;hello&#39;, []],
  [&#39;world&#39;, []],
]);

huangapple
  • 本文由 发表于 2023年6月25日 23:23:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定