英文:
Typescript: Dictionnary whose value type are inferred from key
问题
在TypeScript中,是否可以构建一个字典,其中类型的类型可以从键中推断出来?
在TypeScript中是否可以实现以下行为?
interface Foo {
kind: 'foo',
info: string,
someProperty: string
}
interface Bar {
kind: 'bar',
info: string,
otherProperty: string
}
// 我认为可以通过使用泛型来实现这个目标
type Dictionary = { [type in 'a' | 'b']: (item: TypeInferredFromKey) => void };
const a: Dictionary = {
'foo': (item: Foo) => { ... },
'bar': (item: Bar) => { ... }
}
英文:
Is it possible in typescript, to build a dictionary where the type of the type would be inferred from the key ?
Is it possible to achieve the below behavior in typescript ?
interface Foo {
kind: 'foo',
info: string,
someProperty: string
interface Bar {
kind: 'bar',
info: string,
otherPropery: string
// I think this might be achieved by using generics
type Dictionnary = { [type in 'a' | 'b' ]: (item: TypeInferredFromKey) => void };
const a: Dictionnary = {
'foo': (item: Foo) => { ... }
'bar': (item: Bar) => { ... }
}
答案1
得分: 0
不能将string
转换为完全相同名称的类型,因此我们需要存储一个字典,其中键是字符串(类型的名称),值是类型本身:
interface Foo {
kind: 'foo';
info: string;
someProperty: string;
}
interface Bar {
kind: 'bar';
info: string;
otherProperty: string;
}
type TypeMap = {
foo: Foo;
bar: Bar;
};
现在,只需使用映射类型(mapped types),您可以创建字典类型,其中键是类型的名称,值是接受相应类型项目的函数:
type Dictionary = { [K in keyof TypeMap]: (item: TypeMap[K]) => void };
测试:
const a: Dictionary = {
foo: (item: Foo) => {},
bar: (item: Bar) => {},
};
英文:
It is not possible to convert string
to the type with the exact same name, thus we will need to store some dictionary where keys are the strings(name of the types) and values are the types themselves:
interface Foo {
kind: 'foo';
info: string;
someProperty: string;
}
interface Bar {
kind: 'bar';
info: string;
otherPropery: string;
}
type TypeMap = {
foo: Foo;
bar: Bar;
};
Now, simply with mapped types you can create the dictionary type, where keys are the names of the types and values are the functions accepting an item of the relevant type:
type Dictionary = { [K in keyof TypeMap]: (item: TypeMap[K]) => void };
Testing:
const a: Dictionary = {
foo: (item: Foo) => {},
bar: (item: Bar) => {},
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论