TypeScript 如果我给最后一个数组解构元素命名,会出现编译错误,

imzjd6km  于 5个月前  发布在  TypeScript
关注(0)|答案(3)|浏览(70)

TypeScript版本: v4.0.5
搜索词: destructuring assignment , Object literal may only specify known properties
代码

declare function foo<T extends { dataType: 'a' | 'b'; }>(template: T): [T, any, any]; //<-- there no error, when it is [any,any,any]
declare function bar<T extends { dataType: 'a' | 'b'; }>(template: T): [T, any];

function test_foo() {

  const [, ,] = foo({ dataType: 'a', day: 0 });
  const [x, y, z] = foo({ dataType: 'a', day: 0 });
  const [, , t] = foo({ dataType: 'a', day: 0 }); //<-- red line under the `day`
  console.log(x, y, z, t);
}

function test_bar() {

  const [,] = bar({ dataType: 'a', day: 0 });
  const [x, y] = bar({ dataType: 'a', day: 0 });
  const [, z] = bar({ dataType: 'a', day: 0 });//<-- red line under the `day`
  console.log(x, y, z);
}

预期行为:

无编译错误

实际行为:

Argument of type '{ dataType: "a"; day: number; }' is not assignable to parameter of type '{ dataType: "a" | "b"; }'. Object literal may only specify known properties, and 'day' does not exist in type '{ dataType: "a" | "b"; }'.

Playground链接:

link

相关问题:

vh0rcniy

vh0rcniy1#

你好,我们是一个研究团队,致力于开发机器学习技术来定位适合新手的问题。我们的模型认为这个问题很可能是一个“好的初始问题”。我们建议您将其标记为“好的初始问题”,以便新手知道从哪里开始选择?
谢谢!

aor9mmx1

aor9mmx12#

这不是一个好的首要问题。

6vl6ewon

6vl6ewon3#

你好,我是Repro bot。我可以协助缩小范围并跟踪编译器错误!此评论反映了问题正文中运行的针对夜间TypeScript的重现状态。
问题正文代码块由@heroboy提供
❌ 失败:-

  • Object literal may only specify known properties, and 'day' does not exist in type '{ dataType: "a" | "b"; }'.
  • Object literal may only specify known properties, and 'day' does not exist in type '{ dataType: "a" | "b"; }'.

历史信息
| 版本 | 重现输出 |
| ------------ | ------------ |
| 4.2.2, 4.3.2, 4.4.2, 4.5.2, 4.6.2 | ❌ 失败:-* Argument of type '{ dataType: "a"; day: number; }' is not assignable to parameter of type '{ dataType: "a" | "b"; }'. Object literal may only specify known properties, and 'day' does not exist in type '{ dataType: "a" | "b"; }'.* Argument of type '{ dataType: "a"; day: number; }' is not assignable to parameter of type '{ dataType: "a" | "b"; }'. Object literal may only specify known properties, and 'day' does not exist in type '{ dataType: "a" | "b"; }'. |

相关问题