function customFunction<T>(defaultValue?: T) { return defaultValue; }
const definitelyNullOrUndefined = customFunction<string>(); // type: string | undefined
const definitelyStringType = customFunction<string>('foobar'); // type: string | undefined
Is there a way to modify customFunction()
so that definitelyNullOrUndefined
is automatically set to undefined
, while definitelyStringType
is automatically set to string
?
Overview
I am interested in enhancing a function I am currently utilizing. This function is defined as
function customFunction<T>(obj: { [key: string]: T }, key: string, defaultValue?: T)
and it retrieves the value of key[obj]
if it exists, otherwise using defaultValue
. Even when a defaultValue
is provided, Typescript interprets the return type as T | undefined
.