使用TypeScript的条件类型 [英] Conditional types with TypeScript

查看:140
本文介绍了使用TypeScript的条件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个:

type TypeMapping = {
  Boolean: boolean,
  String: string,
  Number: number,
  ArrayOfString: Array<string>,
  ArrayOfBoolean: Array<boolean>
}

export interface ElemType {
  foo: keyof TypeMapping,
  default: valueof TypeMapping
}

不是要默认使用any,而是要有条件地定义它,我尝试了以下方法:

instead of using any for default, I want to conditionally define it, I tried this:

export interface ElemType<T extends TypeMapping> {
  foo: keyof T,
  default: T
}

但这似乎不太正确,有人知道这样做的正确方法吗?

but that doesn't seem quite right, does anyone know the right way to do this?

如果不清楚,对于任何类型为ElemType的给定对象,foo指向的键必须与foo指向的值匹配.例如,这是有效的:

if it's not clear, for any given object that has type ElemType, the key that foo points to, must be matched by the value that foo points to. For example, this is valid:

{
  foo: 'String',
  default: 'this is a string'
}

但这不是:

{
  foo: 'Boolean',
  default: 'this should be a boolean instead'
}

因此,默认字段的类型在类型字段的值/类型上为有条件的.

so the type of the default field is conditional on the value/type of the type field.

简洁,如果foo'ArrayOfBoolean',则default应该是:Array<boolean>.如果foo'Number',则默认值应为number,如果foo为'Boolean',则默认值应为boolean,依此类推.

Succintly, if foo is 'ArrayOfBoolean', then default should be: Array<boolean>. If foo is 'Number', then default should be number, if foo is 'Boolean' then default should be boolean, etc etc.

推荐答案

您可以像Catalyst的回答中那样定义ElemType,然后使用映射类型对所有可能的K进行ElemType的并集:

You can define ElemType as in Catalyst's answer and then use a mapped type to take the union of ElemType for all possible K:

interface ElemType<K extends keyof TypeMapping> {
  foo: K;
  default: TypeMapping[K];
}
type ElemTypeMap = {[K in keyof TypeMapping]: ElemType<K>};
// type ElemTypeMap = {
//   Boolean: {foo: "Boolean", default: boolean},
//   String: {foo: "String", default: string},
//   ...
// }
type SomeElemType = ElemTypeMap[keyof TypeMapping];
// Look up in ElemTypeMap by all keys and take the union:
// {foo: "Boolean", default: boolean} | {foo: "String", default: string} | ...

这篇关于使用TypeScript的条件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆