Home > Mobile >  TypeScript: how to make a property conditional from an existing type?
TypeScript: how to make a property conditional from an existing type?

Time:07-15

So let's say I have

type Link = {
  text: string;
  link: string;
}

interface BigLink extends Link {
  some: number;
  something: string;
  else: string;
}

but I have a variable that shares all these properties except that the link property can be optional. I don't want to create a whole new type just to change one field to link?: string. Is there a way to do something like

type OptionalBigLink = BigLink & { link?: string }

so that I can overwrite the link field and make it optional. ^ The above code still throws an error when I don't pass in the link property.

CodePudding user response:

Yes you can.

type OptionalBigLink = Partial<Pick<BigLink, "link">> & Omit<BigLink, "link">;

Some tests in the playground

CodePudding user response:

You can use Omit to remove the property from BigLink and then do the intersection.

type OptionalBigLink = Omit<BigLink, "link"> & { link?: string }
  • Related