Skip to content

Instantly share code, notes, and snippets.

@mbjelac
Last active October 9, 2020 17:02
Show Gist options
  • Save mbjelac/e35c85f2fc28bb45223faeac6fe46af7 to your computer and use it in GitHub Desktop.
Save mbjelac/e35c85f2fc28bb45223faeac6fe46af7 to your computer and use it in GitHub Desktop.
A test demonstrating Typescript does not support "deep" default params, i.e. the default params do not extend to object properties.
interface Params {
foo?: string;
bar?: number;
}
function doStuff(params: Params = { foo: "Default", bar: 42}): any[] {
return [params.bar, params.foo];
}
describe("default params", () => {
const examples: ([Params, any[]])[] = [
[undefined, [42, "Default"]],
[{}, [42, "Default"]],
[{foo: "FOO"}, [42, "FOO"]],
[{bar: 13}, [13, "Default"]],
[{foo: "Barf", bar: 17}, [17, "Barf"]],
];
examples.forEach(example => it(JSON.stringify(example), () => {
const [params, result] = example;
expect(doStuff(params)).toEqual(result);
}));
});
@mbjelac
Copy link
Author

mbjelac commented Oct 9, 2020

Only the first and last test pass, namely:

  • undefined params are replaced with the default params value { foo: "Default", bar: 42}
  • fully defined params are of course processed correctly

In all the in-between cases, the default value is undefined since when we provide an object, the entire params is taken as provided and no default values are being substituted.

Kind of reasonable, but sometimes tricky to see immediately.

@mbjelac
Copy link
Author

mbjelac commented Oct 9, 2020

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