it-source

소스에 X개의 요소가 있지만 대상에는 1개만 허용됩니다.

criticalcode 2023. 6. 30. 22:25
반응형

소스에 X개의 요소가 있지만 대상에는 1개만 허용됩니다.

형식 스크립트 컴파일에 다음 오류가 표시됩니다.

소스에 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}?

저도 같은 문제가 있었습니다.교정기는 다음 유형을 따라야 합니다.

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

그래야 한다

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

이것을 기억하는 쉬운 방법은 객체를 유형으로 대체하고 다음과 같이 의미가 있는지 확인하는 것입니다.

[string]효과는 없지만,string[]한다

[{id: FooOperation, display: string}]딱 하나의 요소로 이루어진 튜플을 정의합니다.

시도:

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[] = [...];
const sendArr
    : [{
      entity: string | number | undefined,
      identifier: Array<string | Types.ObjectId | undefined>//[Types.ObjectId | string | undefined]
    }] = [{
      entity: '',
      identifier: [undefined]
    }]

언급URL : https://stackoverflow.com/questions/64308563/source-has-x-elements-but-target-allows-only-1

반응형