Skip to content

Instantly share code, notes, and snippets.

@emmiep
Created May 30, 2018 11:02
Show Gist options
  • Save emmiep/cc90cbf1ebdf88228fbaef5cfdc5a8ca to your computer and use it in GitHub Desktop.
Save emmiep/cc90cbf1ebdf88228fbaef5cfdc5a8ca to your computer and use it in GitHub Desktop.
Fun with TS Extract/Exclude
type PartialOptional<T extends U, U> =
{ [P in Extract<keyof T, keyof U>]: T[P] } &
{ [P in Exclude<keyof T, keyof U>]?: T[P] };
interface DetailedPerson {
name: string
age: number
isCool: boolean
}
interface Person {
name: string
}
type OptionallyDetailedPerson = PartialOptional<DetailedPerson, Person>;
const person1: Person = {
name: 'Alice'
};
const person2: DetailedPerson = {
name: 'Bob',
age: 35,
isCool: false
};
const optional1: OptionallyDetailedPerson = person1; // works
const optional2: OptionallyDetailedPerson = person2; // works
const person3: Person = optional2; // works
const person4: DetailedPerson = optional1; // doesn't work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment