Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

how to remove properties via mapped type in TypeScript

Here is the code

class A {
    x = 0;
    y = 0;
    visible = false;
    render() {

    }
}

type RemoveProperties<T> = {
    readonly [P in keyof T]: T[P] extends Function ? T[P] : never//;
};


var a = new A() as RemoveProperties<A>
a.visible // never
a.render() // ok!

I want to remove " visible / x / y " properties via RemoveProperties ,but I can only replace it with never

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the same trick as the Omit type uses:

// We take the keys of P and if T[P] is a Function we type P as P (the string literal type for the key), otherwise we type it as never. 
// Then we index by keyof T, never will be removed from the union of types, leaving just the property keys that were not typed as never
type JustMethodKeys<T> = ({[P in keyof T]: T[P] extends Function ? P : never })[keyof T];  
type JustMethods<T> = Pick<T, JustMethodKeys<T>>; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...