Search code examples
typescriptdesign-patternstypesinterfacedry

How to optimize the usage of interface object when in one case you need optional properties, but not in another one?


I have the following interface:

interface IUserInfo {
    name: string,
    surname: string,
    dateOfBirth: Date
}

In some places of my app I need to be sure developer provides an object of IUserInfo with all properties to a function:

const someFunc = (state: IUserInfo) => {
    // I want to get an error if developer tries to pass an object without name, surname or dateOfBirth
}

In other cases I need to have possibility to pass an object of the same type, but with optional properties, so user should be able to pass any combination of name/surname/dateOfBirth or nothing.

The easiest way is just implement two interfaces, one with required properties and another one without it. But I feel there is better approach exists to do it allowing don't repeat yourself.

How can realize my requirements the best way?


Solution

  • If you need to just mark all the fields as optional, you can use built-in Partial<T> type like this:

    type IPartialUserInfo = Partial<IUserInfo>;
    // now type IUserInfo = {
    //    name?: string | undefined;
    //    surname?: string | undefined;
    //    dateOfBirth?: Date | undefined;
    // }
    

    You can try it out here.