Skip to content

Instantly share code, notes, and snippets.

@rsms
Created July 28, 2017 16:11
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsms/60e8304808a1b801e8234f3bef5fcb05 to your computer and use it in GitHub Desktop.
Save rsms/60e8304808a1b801e8234f3bef5fcb05 to your computer and use it in GitHub Desktop.
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"
@usernamehw
Copy link

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

type OptionalFoo = Partial<Foo>

@jasonzhouu
Copy link

jasonzhouu commented Jun 24, 2021

@rsms
Copy link
Author

rsms commented Jun 24, 2021

Nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment