考虑以下示例.
enum DialogType {
Options,
Help
}
class Dialog {
test() : string {
return "";
}
}
class Greeter {
openDialogs: { [key in DialogType]: Dialog | undefined } = {
0: undefined,
1: undefined
};
getDialog(t: DialogType) {
return this.openDialogs[t];
}
}
const greeter = new Greeter();
const d = greeter.getDialog(DialogType.Help);
if (d) document.write(d.test());
Run Code Online (Sandbox Code Playgroud)
它有3个问题/问题:
我正在尝试执行以下操作:
interface Collection {
foo: string,
bar: string
}
const patchCollection = (
collection: Collection,
propertyToUpdate: {[key: keyof Collection]: any}
) => {
// do something here
}
Run Code Online (Sandbox Code Playgroud)
目标是拥有key: "foo" | "bar"但我收到以下错误:
索引签名参数类型不能是文字类型或泛型类型。考虑使用映射对象类型代替
但我不确定映射对象在这里如何应用。有什么帮助吗?谢谢!
编辑:
由于存在类似的问题,该问题已结束。我尝试了那里提供的解决方案,但没有设法使其与Mapped type一起使用。但是,我能够使用部分实用程序类型解决我的问题(https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)
interface Collection {
foo: string,
bar: string
}
const patchCollection = (
collection: Collection,
propertyToUpdate: Partial<Collection>
) => {
// do something here
}
Run Code Online (Sandbox Code Playgroud)
这还解决了将正确的值类型与正确的键关联的问题(我之前没有解决这个问题)。我不确定我是否以错误的方式使用映射和索引类型(以及是否有办法用它们来实现它),但Partial绝对看起来是我从一开始就应该采取的正确方法。