Created
July 28, 2017 16:11
-
-
Save rsms/60e8304808a1b801e8234f3bef5fcb05 to your computer and use it in GitHub Desktop.
Make a TypeScript interface completely optional
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
// Optional declares a type of keyed type T where all keys are optional. | |
// This allows | |
type Optional<T> = { [P in keyof T]? :T[P] } | |
interface Foo { | |
x :number | |
y :number | |
} | |
type OptionalFoo = Optional<Foo> | |
// OptionalFoo == interface Foo { | |
// x? :number | |
// y? :number | |
// } | |
function fooify(extraFoo :OptionalFoo) :Foo { | |
const baseFoo :Foo = getBaseFoo() | |
return Object.assign({}, baseFoo, extraFoo) | |
} | |
fooify({x:3}) // returns a valid Foo | |
fooify({z:4}) // error: no "z" property in OptionalFoo | |
fooify({y:'5'}) // error: bad type "string" for property y; expected "number" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Built in Partial:
https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype