Does Typescript support “subset types”?

后端 未结 7 1733
青春惊慌失措
青春惊慌失措 2020-12-29 02:36

Let\'s say I have an interface:

interface IUser {
  email: string;
  id: number;
  phone: string;
};

Then I have a function that expects a

7条回答
  •  执笔经年
    2020-12-29 02:44

    You can seperate it into different interfaces:

    interface IUser {
        id: number;
    };
    
    interface IUserEmail extends IUser {
        email: string;
    }
    
    interface IUserPhone extends IUser {
        phone: string;
    }
    

    Have your method receive the base IUser interface and then check for the fields you need:

    function doit(user: IUser) {
        if (user.email) {
    
        } else if (user.phone) {
    
        }
    }
    

提交回复
热议问题