TS18048

error TS18048: ‘text‘ is possibly ‘undefined‘.

Broken Code ❌

1
2
3
function getShortenedText(text?: string): string {
return text.slice(0, 5);
}

Fixed Code ✔️

If the text parameter is optional, it can potentially be of type unknown. When the type is unknown, accessing methods like Array.slice is not possible.

To solve this error, we need to employ a type guard to ensure that text is of type string:

1
2
3
4
5
6
function getShortenedText(text?: string): string {
if (typeof text === 'string') {
return text.slice(0, 5);
}
return '';
}

Note: We also need to employ a default return value to maintain the function return type of string.