I need to create a function that returns number
if an optional value is provided, and number | null
if not.
So far I've tried:
type GetValueFn = {
(values: { defaultValue: number }): number | null;
(values: { defaultValue: undefined }): number;
}
const getValue: GetValueFn = ({ defaultValue }) => {
const randomValue = Math.ceil(Math.random() * 10)
if (randomValue !== 5) return randomValue;
if (defaultValue !== undefined) return defaultValue;
return null;
}
But I get an error saying:
Type 'null' is not assignable to type 'number'
What's the correct way of doing this?
CodePudding user response:
Yo can use only one definition.
?
= undefined
type GetValueFn = (values: { defaultValue?: number }): number | null;
const getValue: GetValueFn = ({ defaultValue }) => {
const randomValue = Math.ceil(Math.random() * 10)
if (randomValue !== 5) return randomValue;
if (!defaultValue) return defaultValue;
return null;
}
CodePudding user response:
Apparently, function overloads in typescript still doesn't work correctly for arrow functions. more here. I don't know if this is still accurate. If you have the option to, you can declare the function like and it'll work correctly.
interface Values {
defaultValue: number;
}
function getValue(values: Values) : number;
function getValue(values: Partial<Values>) : number | null;
function getValue(values: Values | Partial<Values>) {
const randomValue = Math.ceil(Math.random() * 10)
if (randomValue !== 5) return randomValue;
if (values.defaultValue !== undefined) return values.defaultValue;
return null;
}
Working in TS playground