Reputation: 177
Typescript newbie here.
A component in React receives a prop of a certain type. This prop is then further used to do a bunch of other stuff.
The component:
const ComponentA : SomeComponent<{
dateVal?: string
}> = ({
dateVal
}) => {....}
dateVal
is a string
because there already is some code that requires it to be this way.
I now want to use an existing helper function and pass dateVal
as an argument.
The helper function:
export const helperFunction = (param1?: Param1, date?: Date): string | null => {...}
How do I use helperFunction
since the argument needs to be of type Date
?
I tried calling it like this helperFunction(param1, new Date(dateVal))
but I get the error Argument of type 'string | undefined' is not assignable to parameter of type 'string | number'.
What is the best way around this? Is there a way in Typescript to pass a parameter by explicitly defining its type? Or can I add some conditional logic to pass the parameter?
Upvotes: 1
Views: 1956
Reputation: 8718
The problem is that the new Date(dateVal)
constructor expects dateVal
to be a string or a number. You're passing dateVal
of the type string | undefined
, since it's optional.
If you're 100% sure that dateVal
is a string, you can use an exclamation mark to tell TypeScript "I'm sure this isn't undefined
or null
", like so:
helperFunction(param1, new Date(dateVal!))
Of course, usually you'd use a type guard, and TypeScript would realize dateVal
has to be a string, for example:
if (!dateVal) {
// We know dateVal is undefined or the empty string
return; // return something
}
// TypeScript now knows that dateVal has to be a string
// otherwise the if-statement would've returned earlier
helperFunction(param1, new Date(dateVal))
Upvotes: 2