very simple question.. yet I dont know. I have following example from code
interface A {
a:string;
}
interface B extends A{
b:string;
}
const b:B = {
a:'a',
b:'b'
}
const a:A = b;
console.log(a)
The question is. Now it prints both properties ‘a’ and ‘b’. However I would only like to get the A properties excluding the B properties.
Any anser appreciated.
2
Answers
You can use the Pick utility type directly in TypeScript. Here’s an example:
In this example, the Pick<B, keyof A> type is used to extract only the properties defined in interface A from the object b. The spread operator ({ …b }) is then used to create a new object with only the selected properties.
There’s a minor confusion between original purpose of TypeScript and the core of JavaScript. For example, when we mutate or create clones of JavaScript Objects, there is no room for TS by default.
In your question, you’re creating a reference to existing object instead of cloning a new one. That seems to be a core problem.
This is my approach to the actual given problem (see TS Playground example for details). But check this, if it helps in your case.