Typescript:值类型从键中推断的字典

huangapple go评论62阅读模式
英文:

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) => {},
};

playground

英文:

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) => {},
};

playground

huangapple
  • 本文由 发表于 2023年6月15日 20:27:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76482470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定