Make a single property optional in TypeScript

后端 未结 6 1728
盖世英雄少女心
盖世英雄少女心 2020-12-14 05:42

In TypeScript, 2.2...

Let\'s say I have a Person type:

interface Person {
  name: string;
  hometown: string;
  nickname: string;
}

6条回答
  •  盖世英雄少女心
    2020-12-14 06:39

    Ok well what you are really describing is two different "Types" of people (i.e. Person types) .. A normal person and a nick named person.

    interface Person {
        name: string;
        hometown: string;
    }
    
    interface NicknamedPerson extends Person {
        nickname: string;
    }
    

    Then in the case where you don't really want a nicknamed person but just a person you just implement the Person interface.

    An alternative way to do this if you wanted to hang on to just one Person interface is having a different implementation for a non nicknamed person:

    interface Person {
      name: string;
      hometown: string;
      nickname: string;
    }
    class NicknamedPerson implements Person {
        constructor(public name: string, public hometown: string, public nickname: string) {}
    }
    
    class RegularPerson implements Person {
        nickname: string;
        constructor(public name: string, public hometown: string) {
            this.nickname = name;
        }
    }
    
    makePerson(input): Person {
         if(input.nickname != null) {
           return new NicknamedPerson(input.name, input.hometown, input.nickname);
         } else {
           return new RegularPerson(input.name, input.hometown);
         }
    }
    

    This enables you to still assign a nickname (which is just the persons name in case of an absence of a nickname) and still uphold the Person interface's contract. It really has more to do with how you intend on using the interface. Does the code care about the person having a nickname? If not, then the first proposal is probably better.

提交回复
热议问题