【问题标题】:Source has X element(s) but target allows only 1源有 X 个元素,但目标只允许 1 个
【发布时间】:2021-01-26 05:14:39
【问题描述】:

打字稿编译显示此错误:

源有 X 个元素,但目标只允许 1 个。

export const FooMapping: [{id: FooOperation, display: string}] = [
    { id: FooOperation.Undefined, display: 'Nothing' },
    { id: FooOperation.A, display: 'I'm A' },
    { id: FooOperation.B, display: 'I'm B' }
];

export enum FooOperation {
    Undefined = 0,
    A = 1,
    B = 2,
}

定义{id: FooOperation, display: string}的特殊对象数组的正确方法是什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    [{id: FooOperation, display: string}] 定义了恰好一个元素的 tuple

    试试:

    export const FooMapping: Array<{id: FooOperation; display: string}> = [
        { id: FooOperation.Undefined, display: 'Nothing' },
        { id: FooOperation.A, display: "I'm A" },
        { id: FooOperation.B, display: "I'm B" }
    ];
    

    或者考虑一下:

    interface Foo {
      id: FooOperation;
      display: string;
    }
    
    export const FooMapping: Foo[] = [...];
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。大括号必须跟在类型之后:

      const FooMapping: [{id: FooOperation, display: string}] 
      

      应该是

      const FooMapping: {id: FooOperation, display: string}[] 
      

      记住这一点的简单方法是将对象替换为类型,看看它是否有意义:

      [string] 不起作用,但 string[] 起作用

      【讨论】:

      • 对这个字面意思是捂脸。感谢您的回答。
      【解决方案3】:
      const sendArr
          : [{
            entity: string | number | undefined,
            identifier: Array<string | Types.ObjectId | undefined>//[Types.ObjectId | string | undefined]
          }] = [{
            entity: '',
            identifier: [undefined]
          }]
      

      【讨论】:

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