source

"대신 매핑된 개체 유형을 사용하는 것을 고려하십시오." - 매핑된 개체 유형은 무엇이며 여기서 어떻게 사용합니까?

myloves 2023. 3. 29. 22:06

"대신 매핑된 개체 유형을 사용하는 것을 고려하십시오." - 매핑된 개체 유형은 무엇이며 여기서 어떻게 사용합니까?

이 타입스크립트 코드를 컴파일하려고 하면

interface Foo { 
    [foo: "hello" | "world"]: string;
}

이 에러 메세지가 표시됩니다.

An index signature parameter type cannot be a union type. Consider using a mapped object type instead.

매핑된 오브젝트유형은 무엇이며 어떻게 사용합니까?

매핑된 오브젝트타입은 싱글톤타입의 세트로 동작하며 각각의 싱글톤이 속성명으로 변환되는 새로운 오브젝트 타입을 생성합니다.

예를 들어 다음과 같습니다.

type Foo = {
    [K in "hello" | "world"]: string
};

와 동등하다

type Foo = {
    "hello": string;
    "world": string;
};

매핑된 오브젝트타입은 고유 타입 연산자이며, 중괄호의 구문은 인터페이스 또는 다른 멤버와의 오브젝트타입에서는 사용할 수 없습니다.예를들면

interface Foo {
    [K in "hello" | "world"]: string; // ❌
}

그럼 다음 오류가 발생합니다.

A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.

매핑된 개체 유형은 많은 다른 작업에 유용합니다.자세한 내용은 이쪽:https://www.typescriptlang.org/docs/handbook/2/mapped-types.html

이것은 무효입니다.

    type DirectiveType = 'package-as' | 'externals' | 'move-folders' | 'ignore';
    type Directives = { [key:DirectiveType]?: RootDirectives };
    
    export class PkgmetaFile {
        private _directives: Directives = {};
    }

하지만 이것은 유효합니다.

    type DirectiveType = 'package-as' | 'externals' | 'move-folders' | 'ignore';
    type Directives = { [Key in DirectiveType as string]?: RootDirectives };
    
    export class PkgmetaFile {
        private _directives: Directives = {};
    }

언급URL : https://stackoverflow.com/questions/51659420/consider-using-a-mapped-object-type-instead-whats-a-mapped-object-type-and