interface Foo {
[foo: "hello" | "world"]: string;
}
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息
An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
Run Code Online (Sandbox Code Playgroud)
什么是映射对象类型,以及如何使用它?
Dan*_*ser 24
映射对象类型对一组单例类型进行操作,并生成一个新的对象类型,其中每个单例都转换为属性名称.
例如,这个:
type Foo = {
[K in "hello" | "world"]: string
};
Run Code Online (Sandbox Code Playgroud)
相当于
type Foo = {
"hello": string;
"world": string;
};
Run Code Online (Sandbox Code Playgroud)
请记住,映射的对象类型是一个不同的类型操作符 - 大括号中的语法不能用于接口,也不能用于与其他成员的对象类型.例如
interface Foo {
[K in "hello" | "world"]: string
}
Run Code Online (Sandbox Code Playgroud)
产生以下错误:
A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.
Run Code Online (Sandbox Code Playgroud)
映射的对象类型对许多不同的东西都很有用.在这里阅读更多内容:http://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types
Chr*_*der 17
这是无效的:
type DirectiveType = 'package-as' | 'externals' | 'move-folders' | 'ignore';
type Directives = { [key:DirectiveType]?: RootDirectives };
export class PkgmetaFile {
private _directives: Directives = {};
}
Run Code Online (Sandbox Code Playgroud)
但这是有效的:
type DirectiveType = 'package-as' | 'externals' | 'move-folders' | 'ignore';
type Directives = { [Key in DirectiveType as string]?: RootDirectives };
export class PkgmetaFile {
private _directives: Directives = {};
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4267 次 |
最近记录: |