【问题标题】:TypeScript Named Tuple - Target requires 1 element(s) but source may have fewer.(2345)TypeScript 命名元组 - 目标需要 1 个元素,但源可能有更少。(2345)
【发布时间】:2022-01-23 23:24:57
【问题描述】:

我正在尝试利用命名元组(在本例中为 AnniversaryPropertyConfig 在以下简化代码中描述函数参数。

interface AnniversaryParameters {
    value?: 'date-and-or-time' | 'text';
    altid?: number | string;
    calscale?: 'gregorian';
}

type AnniversaryPropertyConfig = [value: string, parameters?: AnniversaryParameters];

function main(config: AnniversaryPropertyConfig) {
    return config;
}

const config = ['19960415', { value: 'text' as const }];

main(config);

但是我一直收到以下错误:“目标需要 1 个元素,但源可能有更少。(2345)”我尝试将 as const 断言应用于 config 数组及其值,但徒劳无功。如果我将 config 变量类型转换为 AnniversaryPropertyConfig 类型,该错误就会消失。但我觉得这是 TypeScript 在没有帮助的情况下应该能够推断出的东西。

可在here 找到适用的 TypeScript Playground 的链接作为参考。

【问题讨论】:

    标签: typescript types tuples typechecking


    【解决方案1】:

    我发现摆脱错误的唯一方法是这样做:

    const config = ['19960415', { value: 'text' }] as AnniversaryPropertyConfig;

    ...或...

    const config: AnniversaryPropertyConfig = ['19960415', { value: 'text' }];

    据我猜测,TypeScript 的类型推断将 ['19960415', { value: 'text' }] 视为一个数组,该数组可以在数组中的任何位置包含字符串,或者在数组中的任何位置与 { value: 'text' } 匹配的对象。因此推断的类型对数组元素没有任何强制顺序,使其过于宽泛而无法自动同意AnniversaryPropertyConfig

    【讨论】:

      【解决方案2】:

      您的问题是您将AnniversaryPropertyConfig 定义为tuple[value: string, parameters?: AnniversaryParameters]

      数组永远不会被推断为元组,因此您必须明确声明类型。

      interface AnniversaryParameters {
          value?: 'date-and-or-time' | 'text';
          altid?: number | string;
          calscale?: 'gregorian';
      }
      
      type AnniversaryPropertyConfig = [value: string, parameters?: AnniversaryParameters];
      
      function main(config: AnniversaryPropertyConfig) {
          return config;
      }
      
      const config: AnniversaryPropertyConfig = ['19960415', { value: 'text' }];
      
      main(config);
      

      帮自己一个忙,一定要避免键入myVar as MyType 之类的断言。这绝不是一个好主意。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-06
        • 2021-01-26
        • 2021-09-14
        • 1970-01-01
        • 2022-01-21
        • 2019-08-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多