Created
May 30, 2018 11:02
-
-
Save emmiep/cc90cbf1ebdf88228fbaef5cfdc5a8ca to your computer and use it in GitHub Desktop.
Fun with TS Extract/Exclude
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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