为什么下面的代码没有经过类型检查(TypeScript 5.5.4):
type ValidationResult$Type = 'success' | 'invalid_or_expired_token'
export type ValidationResult = {
type: 'success'
token_info: object
} | {
type: 'invalid_or_expired_token'
};
const x: ValidationResult = undefined as unknown as ValidationResult;
const {type}: {type: ValidationResult$Type} = x;
switch (type) {
case 'success':
const {token_info} = x;
break;
case 'invalid_or_expired_token':
break;
}
而下面更简单的代码可以做到:
// type ValidationResult$Type = 'success' | 'invalid_or_expired_token'
export type ValidationResult = {
type: 'success'
token_info: object
} | {
type: 'invalid_or_expired_token'
};
const x: ValidationResult = undefined as unknown as ValidationResult;
// const {type}: {type: ValidationResult$Type} = x;
const {type} = x;
switch (type) {
case 'success':
const {token_info} = x;
break;
case 'invalid_or_expired_token':
break;
}