面试题答案
一键面试- 定义函数参数类型:
在TypeScript中,可以使用联合类型
|
来表示参数可能为null
或undefined
。例如,如果函数接收一个字符串类型的值,但这个值可能为null
或undefined
,可以这样定义参数类型:function processValue(value: string | null | undefined) { // 函数内部处理 }
- 函数内部处理:
- 使用类型断言:如果确定值不为
null
或undefined
,可以使用类型断言。但要注意,使用不当可能导致运行时错误。
function processValue(value: string | null | undefined) { if (value) { const strValue = value as string; console.log(strValue.length); } }
- 使用可选链操作符(
?.
):这是一种更安全的处理方式,它允许在对象属性访问或函数调用时,如果对象为null
或undefined
,表达式不会报错,而是返回undefined
。
function processValue(value: string | null | undefined) { const length = value?.length; console.log(length); }
- 使用
NonNullable
类型:NonNullable
类型可以从联合类型中排除null
和undefined
。
不过在上述代码中,需要确保function processValue(value: string | null | undefined) { const nonNullValue: NonNullable<typeof value> = value as NonNullable<typeof value>; console.log(nonNullValue.length); }
value
不为null
或undefined
,否则会有运行时错误,所以一般会结合if
语句先进行判断。function processValue(value: string | null | undefined) { if (value) { const nonNullValue: NonNullable<typeof value> = value as NonNullable<typeof value>; console.log(nonNullValue.length); } }
- 使用类型断言:如果确定值不为