Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Created June 16, 2017 23:15
Show Gist options
  • Save OliverJAsh/fe1b1b44c5270baa470cebc5dc3efa2f to your computer and use it in GitHub Desktop.
Save OliverJAsh/fe1b1b44c5270baa470cebc5dc3efa2f to your computer and use it in GitHub Desktop.
TypeScript: function object parameter with defaults
{
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