Background
I'm using React and TypeScript and trying to add an optional parameter to a component. Then I run into a typescript error (ts:2339).
It seems that, when no props is passed, React will pass props={}
instead of props=null
or props=undefined
. So the functional component will receive {}
(an empty object), and I cannot change that.
Problem
How should I let TypeScript read the real optional parameters with pre-defined values?
const f = (param: {} | { k: string } = { k: 'v' }) => {
var o
// test 1 TS error: Property 'k' does not exist on type '{} | { k: string; }'. Property 'k' does not exist on type '{}'.(2339)
// o = (param)?.k
// test 2, nullity test. Same error as test1
// if (Object.entries(param).length === 0) param = { k: 'v' };
// o = (param)?.k
// test 3, trying to avoid optional param assignment. Same error as test1
// const _param = param ?? { k: 'v' }
// o = _param.k
// current work-around
o = (param as any)?.k
console.log(o)
}
f()
The param
variable is never empty in this example and always has the property k
. Yet I cannot use param?.k
or anything I can come up with. I know that the any
type works like disabling the TypeScript function. So, is there a way to let TypeScript read the true value of the parameter? Thanks.
What I did
I've read almost all similar questions on Stack Overflow but I see no good answer. Here are some references.
- test2: How do I test for an empty JavaScript object?
- test3: Set default value of property of object passed on parameter to function
- I can't use
null
instead of{}
because of React. - I think this can be helpful but I can't find API on non-route component: React route params with default value .
- This one is with the class component, but not resolving my question: Default property value in React component using TypeScript