"대신 매핑된 개체 유형을 사용하는 것을 고려하십시오." - 매핑된 개체 유형은 무엇이며 여기서 어떻게 사용합니까?
이 타입스크립트 코드를 컴파일하려고 하면
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
'source' 카테고리의 다른 글
| 이 오류 메시지에서 '이 변수를 useEffect 안쪽으로 직접 이동'한다는 것은 무엇을 의미합니까? (0) | 2023.03.29 |
|---|---|
| 어떻게 하면 워드프레스에서 데이터베이스 이름을 얻을 수 있습니까? (0) | 2023.03.29 |
| Django, ReactJS, Webpack 핫 새로고침 (0) | 2023.03.29 |
| 바인딩이 Null/정의되지 않은 경우 Angularjs 템플릿 기본값(필터 포함) (0) | 2023.03.29 |
| 워드프레스에서 여러 meta_key에 대한 사용자 메타 업데이트 방법 (0) | 2023.03.29 |