简体   繁体   English

从TypeScript获取泛型的参数类型

[英]Get parameter type from generic on TypeScript

Suppose I have the following code snippet: 假设我有以下代码片段:

interface Generic <S, T> {
    _?: [S, T];
    id: string;
    ...
}

interface A {}
interface B {}
interface C {}
interface D {}

type t1 = Generic<A, B>;
type t2 = Generic<B, C>;

This is code that I cannot change (from another package). 这是我无法更改的代码(来自另一个包)。 My question is: is there a way for me to find out programatically what are S and T for a given type (eg t1, t2)? 我的问题是:有没有办法让我以编程方式找出给定类型的S和T(例如t1,t2)?

I have a strong suspicion that since this information is lost after compilation, I will never be able to figure out what S and T are at runtime. 我强烈怀疑,由于这些信息在编译后丢失了,我将永远无法弄清楚S和T在运行时是什么。 Even worst, I won't be able to look at details from t1 and t2 ( just like this previous question ). 即使最糟糕的是,我也无法查看t1和t2的详细信息( 就像上一个问题一样 )。

However, since I'm very new to TypeScript, I wonder if I just didn't know the right way to ask, and the internet actually has an answer for me. 但是,由于我对TypeScript很陌生,我想知道我是否只是不知道正确的问题,互联网实际上有一个答案。

So, is it possible? 那么,有可能吗? How? 怎么样?

You are correct that as the TypeScript types are erased at runtime you cannot access them then. 你是正确的,因为在运行时擦除了TypeScript类型,你无法访问它们。 However, you are able to access the types of the generic parameters at compile time using conditional types : 但是,您可以使用条件类型在编译时访问泛型参数的类型

type FirstOfGeneric<G> = G extends Generic<infer F, any> ? F : never;
type SecondOfGeneric<G> = G extends Generic<any, infer S> ? S : never;

// type t1_f = A
type t1_f = FirstOfGeneric<t1>;
// type t1_s = B
type t1_s = SecondOfGeneric<t1>;

You can then use standard TS features like typeguards and casting to act upon the runtime instances of t1_f and t1_s , 然后,您可以使用标准TS功能(如typeguards和cast)来处理t1_ft1_s的运行时实例,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM