skip to Main Content

I’ve a BaseType and a BabyType.

export type BaseType = {
    id: string
}
export type BabyType = BaseType & {
    name: string 
};

I have generic layer where <T extends BaseType>. Actually item is a ‘BabyType’ object.

updateItem(item: T): Promise<T> {
        console.log(data) // {id: '6495f70a317b446b083f', name: 'Test'}

In this layer I want to remove ‘id’ (dynamically) from the data but I want to keep all key what defined in BabyType.

So the excepted result:
console.log(data) // {name: 'Test'}

I’ve tried

type OmitType = Omit<T, keyof BaseType>;
console.log(data as OmitType)

but it does not work. id still logged in console.

Is there any solution to remove all key/value what are come from BaseType.

2

Answers


  1. Chosen as BEST ANSWER

    Looks like it's not possible. (without lib)

    Get keys of a Typescript interface as array of strings

    Thank you @wonderflame for the answers. Finally I used your code.

    const {id, ...rest} = item;
    

  2. Typescript doesn’t affect runtime behavior. Your as assertion only changes how Typescript infers the type but doesn’t modify the JavaScript object.
    This is exactly a showcase of why you should avoid assertions since they can cause misleading types.

    The easiest approach is just destructing the item and divide it into id and the rest:

    export type BaseType = {
        id: string;
    };
    export type BabyType = BaseType & {
        name: string;
    };
    
    function updateItem(item: BabyType){
        const {id, ...rest} = item;
    
        rest
        // ^? const rest = {name: string
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search