在TypeScript中,可以通过使用类型保护和类型断言来防止在使用联合类型时出现赋值错误。
function processValue(value: string | number) {
if (typeof value === 'string') {
// 处理字符串类型
} else {
// 处理数字类型
}
}
function processValue(value: Date | string) {
if (value instanceof Date) {
// 处理日期类型
} else {
// 处理字符串类型
}
}
interface Foo {
foo: string;
}
interface Bar {
bar: number;
}
function isFoo(value: Foo | Bar): value is Foo {
return 'foo' in value;
}
function processValue(value: Foo | Bar) {
if (isFoo(value)) {
// 处理Foo类型
} else {
// 处理Bar类型
}
}
function processValue(value: string | number) {
const strLength = (value as string).length; // 类型断言为字符串类型
const numSquare = (<number>value) ** 2; // 类型断言为数字类型
}
综上所述,通过使用类型保护和类型断言,可以有效防止在TypeScript中使用联合类型时出现赋值错误。
领取专属 10元无门槛券
手把手带您无忧上云