Created
June 16, 2017 23:15
-
-
Save OliverJAsh/fe1b1b44c5270baa470cebc5dc3efa2f to your computer and use it in GitHub Desktop.
TypeScript: function object parameter with defaults
This file contains hidden or 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 All = { foo: string, bar: string }; | |
type Requireds = Pick<All, 'foo'>; | |
type Defaults = Pick<All, 'bar'>; | |
// Our function expects all required fields and any overrides for fields with defaults. | |
type Args = Requireds & Partial<Defaults>; | |
const defaults: Defaults = { bar: 'bar' }; | |
const fn = (args: Args) => { | |
const all: All = { ...defaults, ...args }; | |
}; | |
fn({ foo: 'foo', bar: 'bar' }); // overriding default for bar | |
fn({ foo: 'foo' }); // using default for bar | |
fn({}); // error: foo is required | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment