简体   繁体   English

打字稿->知道给定的接口是否在类型别名中

[英]Typescript -> Know if given interface is in type alias

I have a type alias on multiple interfaces : 我在多个接口上都有类型别名:

export interface A {}
export interface B {}
export interface C {}
export type Reference = A | B | C;

I have a method called getReference which returns, by default, an array of Reference. 我有一个名为getReference的方法,该方法默认情况下返回一个Reference数组。 I would like my method takes a generic type and check if the given type is in my type alias. 我希望我的方法采用通用类型,并检查给定类型是否在我的类型别名中。

That I have : 我有 :

export const getReference = (slug: ReferencesSlugs): (state: object) => Array<Reference> => {
   ....... // some code
   // return Reference[]
}

That I want : 我想要的:

Dev can pass generic type and Typescript check if the given type is in the type alias (Reference). 开发人员可以通过泛型类型和Typescript检查给定类型是否在类型别名中(参考)。

export const getReference = <T>(slug: ReferencesSlugs): (state: object) => Array<T> => {
    ....... // some code
    // As T is in Reference type -> return T[]
}



this.store.pipe( select(getReference<A>('onchonch')) ); // VALID, tslint is ok
this.store.pipe( select(getReference<E>('onchonch')) ); // INAVLID, E is not in my type alias.

Thanks by advance :) 在此先感谢:)

Assuming your union members (the union in the type alias) are not as simple as in your question (ie they have some members) you can use a type constraint on your generic type parameter: 假设您的工会成员(类型别名中的工会)不像您的问题(即他们有一些成员)那样简单,则可以对通用类型参数使用类型约束:

export interface A { a: number; }
export interface B { b: number; }
export interface C { c: number; }
export interface E { e: number; }
export type Reference = A | B | C;

export const getReference = <T extends Reference>(slug: ReferencesSlugs): (state: object) => Array<T> => {
    return null!;
}

getReference<A>('onchonch'); // VALID, tslint is ok
getReference<E>('onchonch'); // INAVLID, E is not in my type alias.

The reason the members matter is because typescript uses structural compatibility to determine type compatibility. 成员之所以重要是因为打字稿使用结构兼容性来确定类型兼容性。 This means if two types have the same fields they will be compatible. 这意味着如果两种类型具有相同的字段,它们将是兼容的。 This also means two empty interfaces are compatible. 这也意味着两个空接口是兼容的。

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

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