索引对象的打字稿参考值

时间:2020-06-26 06:58:36

标签: typescript typescript-typings

我有一个函数可以接收这样定义的对象参数:

interface MyObject {
  [key: string]: (SomeTypeA | SomeTypeB)[]
}

对象的签名是从JSON模式动态生成的,将来可能包含更多属性,但它充当MyObject值的唯一事实来源。当我有对(SomeTypeA | SomeTypeB)[]的引用时,是否可以引用接口的MyObject部分?

例如:像这样:

const doSomething = (withObject: valueof MyObject) => {
 // withObject is either SomeTypeA or SomeTypeB or whatever the value of properties is inside MyObject
}

1 个答案:

答案 0 :(得分:0)

您可以提取以下类型:

type SomeTypeA = string;
type SomeTypeB = number;

interface MyObject {
  [key: string]: (SomeTypeA | SomeTypeB)[],
}

type ExtractType<T> = T[keyof T];

const c: ExtractType<MyObject> = [50, 'foo'];