在处理键重映射联合类型函数时,我们可以采用以下方法来确保安全使用:
type Person = { name: string; age: number; };
type Employee = Person & { company: string; };
type Customer = Person & { address: string; };
function getType(value: Employee | Customer): string { if ('company' in value) { return 'employee'; } else { return 'customer'; } }
type Actions = { type: 'add'; payload: string } | { type: 'remove'; payload: number };
function reducer(state: number[], action: Actions) { switch (action.type) { case 'add': return [...state, action.payload]; case 'remove': return state.filter((_, index) => index !== action.payload); // 如果有其他的操作类型,可以使用never类型来保证代码的正确性 default: const _: never = action; return state; } }