在TypeScript中从类型参数的类型中获取类型参数的类型

时间:2018-03-16 13:35:01

标签: typescript

对于凌乱的标题感到抱歉。我想,举个例子可以说明一点。

--docker.tls.ca=/ssl/ca.pem \
--docker.tls.cert=/ssl/server.pem \
--docker.tls.key=/ssl/server-key.pem \
--docker.tls.insecureSkipVerify

我知道这个例子有点傻,因为我可以定义const array = [ { id: 1, value: 'a' }, { id: 2, value: 'b' }, ]; // A will be the type Array<{ id: number, value: string }> type A = typeof array; // K will be the type of all the keys of Array type like length, toString, ... type K = keyof A; // I wish the below can make T the type { id: number, value: string } type T = paramof A; 之类的接口来获取{ id: number, value: string }。但我的情况是T之类的东西会非常有用。请设想paramof变量不在我的控制之下。

TypeScript允许我们从值中获取类型并从类型中获取所有键。有没有办法从TypeScript?

中的类型参数的类型中获取类型参数的类型

1 个答案:

答案 0 :(得分:1)

在Typescript 2.8中,您可以轻松地针对任何特定的泛型类型执行此操作,而不仅仅是使用条件类型的数组:

type A = typeof array;
// Get the generic 
type AParam = A extends Array<infer T> ? T : never;

在2.7或之前,您只需索引数组以获取项目的类型:

type A = typeof array;
// Item Of A
type AItem = A[0]
// Or 
type AItem2 = typeof array[0]