My function can accept either a string or an object. If it receives an object, it uses the name
property of the object. If it gets a string, it uses the string itself:
const foo = (bar: ({ name: string } | string)) => // accepts string or object
bar?.name ?? bar; // returns string or name property
The issue arises when TypeScript throws this error:
Property 'name' does not exist on type '(string | { name: string; })'.ts(2339)
For example, if I call:
foo('some string');
it results in:
'some string'?.name ?? 'some string'
...which is actually valid code as 'some string'?.name
simply returns undefined
.
One alternative is to create a separate function named isString
and then modify the logic like this:
isString(bar) ? bar : bar.name;
However, this seems like a lot of unnecessary code for such a simple task. Are there any other shorter options besides implementing all that extra code or resorting to using @ts-ignore
?