Last active
October 9, 2020 17:02
-
-
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.
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
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); | |
})); | |
}); |
Here's the official stuff: https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Only the first and last test pass, namely:
undefined
params are replaced with the default params value{ foo: "Default", bar: 42}
In all the in-between cases, the default value is
undefined
since when we provide an object, the entireparams
is taken as provided and no default values are being substituted.Kind of reasonable, but sometimes tricky to see immediately.