Typescript Interface - Possible to make “one or the other” properties required?

前端 未结 6 1790
梦谈多话
梦谈多话 2020-12-02 18:06

Possibly an odd question, but i\'m curious if it\'s possible to make an interface where one property or the other is required.

So, for example...

int         


        
6条回答
  •  旧时难觅i
    2020-12-02 18:30

    You can create few interfaces for the required conditions and join them in a type like here:

    interface SolidPart {
        name: string;
        surname: string;
        action: 'add' | 'edit' | 'delete';
        id?: number;
    }
    interface WithId {
        action: 'edit' | 'delete';
        id: number;
    }
    interface WithoutId {
        action: 'add';
        id?: number;
    }
    
    export type Entity = SolidPart & (WithId | WithoutId);
    
    const item: Entity = { // valid
        name: 'John',
        surname: 'Doe',
        action: 'add'
    }
    const item: Entity = { // not valid, id required for action === 'edit'
        name: 'John',
        surname: 'Doe',
        action: 'edit'
    }
    

提交回复
热议问题