Xiao_e_yun
Xiao_e_yun

Reputation: 348

TypeScript Generic filter

I want filter any have X Object in interface

function hello<T extends keyof I>(type:T,value:I[T]["X"]):void

interface I{
    A:{
        X:any
    }
    B:{
        Y:any
    }
    C:{
        X:any
        Y:any
    }
}

I just hope type is A|C

Upvotes: 0

Views: 142

Answers (1)

ZZB
ZZB

Reputation: 810

I assume you are looking for this?

type FilterKeysToObject<T, V> = {
    [K in keyof T as T[K] extends V ? K : never]: T[K]
};


interface I{
    A:{
        X:any
    }
    B:{
        Y:any
    }
    C:{
        X:any
        Y:any
    }
}

type WithX = FilterKeysToObject<I, {X: any}>;

function hello<K extends keyof WithX>(type:WithX,value:WithX[K]['X']):void {

}

playground

Upvotes: 1

Related Questions