skip to Main Content

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


  1. You can use the Pick utility type directly in TypeScript. Here’s an example:

    interface A {
    a: string;
    }
    
    interface B extends A {
    b: string;
    }
    
    const b: B = {
    a: "a",
    b: "b",
    };
    
    // Use Pick utility type to extract only properties from interface A
    const a: A = { ...b } as Pick<B, keyof A>;
    
    console.log(a); // Output: { a: 'a' }
    

    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.

    Login or Signup to reply.
  2. 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.

    interface All {
        a: string;
        b: string;
    }
    
    type OnlyA = Pick<All, 'a'>;
    
    const ObjectAll: All = { "a": "a", "b": "b" };
    const { a: ObjectA }: OnlyA = ObjectAll;
    
    console.log('ObjectAll', ObjectAll);
    console.log('ObjectA', ObjectA);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search