Make a single property optional in TypeScript

后端 未结 6 1729
盖世英雄少女心
盖世英雄少女心 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:24

    After a lot of digging, I think what I'm trying to do just isn't possible in TypeScript... yet. When spread/rest types land, I think it will be, though, with syntax something along the lines of { ...Person, nickname?: string }.

    For now, I've gone with a more verbose approach, declaring the properties that are required:

    type MakePersonInput = Partial & {
      name: string;
      hometown: string;
    };
    function makePerson(input: MakePersonInput): Person {
      return {...input, nickname: input.nickname || input.name};
    }
    

    This unfortunately requires me to update MakePersonInput whenever I add more required properties to Person, but it's impossible to forget to do this, because it will cause a type error in makePerson.

提交回复
热议问题