面试题答案
一键面试联合类型(Union Types)
- 定义:联合类型表示一个值可以是多种类型中的一种。通过
|
运算符来连接不同的类型。 - 示例:
let value: string | number;
value = 'hello';
value = 42;
在上述代码中,value
变量可以是 string
类型或者 number
类型。
交叉类型(Intersection Types)
- 定义:交叉类型表示一个值必须同时满足多种类型的要求。通过
&
运算符来连接不同的类型。 - 示例:
interface A {
a: string;
}
interface B {
b: number;
}
let obj: A & B = { a: 'test', b: 123 };
在上述代码中,obj
变量必须同时满足 A
接口和 B
接口的要求,即同时拥有 a
属性(类型为 string
)和 b
属性(类型为 number
)。
实际应用场景不同
- 联合类型应用场景:
- 当一个函数参数可以接受不同类型的值,但逻辑上对这些不同类型的值处理方式类似时使用。例如:
function printValue(value: string | number) {
console.log(value);
}
printValue('text');
printValue(100);
- 交叉类型应用场景:
- 用于合并多个对象类型的属性,创建一个新的类型。比如在 React 中定义组件的 props 时,可能需要合并多个不同用途的属性类型。
interface Props1 {
name: string;
}
interface Props2 {
age: number;
}
function MyComponent(props: Props1 & Props2) {
return (
<div>
{props.name} is {props.age} years old.
</div>
);
}
这里 MyComponent
的 props
需要同时具备 Props1
和 Props2
的属性。