我想将一个枚举(或类型,我不确定我的术语是否正确)定义为特定对象,例如:
enum Notes {
{ subDir: "list", desc: "file contains list" },
{ subDir: "maps", desc: "file contains maps" },
}
即类型为Notes的实例,只能是以下类型,并且具有枚举中定义的上述属性:
interface Descriptor {
subDir: string;
desc: string;
}
是否可以通过使用枚举或其他方法实现?
这是我最想要实现的目标,但是我无法将类型本身视为Descriptor的实例:
type Notes =
{ subDir: "list", desc: "file contains lists" } |
{ subDir: "map", desc: "file contains maps" };
interface Descriptor {
subDir: string;
desc: string;
}
答案 0 :(得分:0)
不,枚举在此处使用的构造/类型错误。我认为您只需要一个名为Notes
的数组,其中包含一个或多个符合接口Descriptor
Notes: Descriptor[] = [
{ subDir: "list", desc: "file contains list" },
{ subDir: "maps", desc: "file contains maps" }];
答案 1 :(得分:0)
您的Notes
类型在更大的界面中对我有用:
type Notes =
{ subDir: "list", desc: "file contains lists" } |
{ subDir: "map", desc: "file contains maps" };
interface BiggerInterface {
notes: Notes[];
}
let b1: BiggerInterface = {
notes: [ // OK
{ subDir: "list", desc: "file contains lists" },
{ subDir: "map", desc: "file contains maps" },
]
};
let b2: BiggerInterface = {
notes: [ // error
{ subDir: "list", desc: "file contains something else" }
]
};
如果这不是您的初衷,请澄清问题。