Skip to content

Instantly share code, notes, and snippets.

@rsms rsms/optional.ts
Created Jul 28, 2017

What would you like to do?
Make a TypeScript interface completely optional
// 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"

This comment has been minimized.

Copy link

usernamehw commented Aug 15, 2019

Partial<T> is provided by TypeScript 2.1+ by default:

type OptionalFoo = Partial<Foo>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.