分配到(或断言)never
在函数的末尾全面性检查是为了迫使详尽检查编译时用于打字稿使用的技术。没有明确串
但是,为了让编译器检测到这一点,它需要显式字符串来检查以确定函数是否在never
的赋值/断言之前确实返回。
有没有可能引进某种Object.freeze的类型变化,仅适用于对象的文字,并进一步与链,使像下面可以做?
更好的是,有没有办法创建一个接口,其中的按键自动为的Action.type(本例中为)?如果是这种情况 - actionMap
可以简单地声明为该接口,这将强制在编译时检查。
两者都是同样的问题......只给一个识别联合解决方案,是有可能做全面性检查,这样,在编译时,无需在函数中使用明确的字符串?
interface Increment {
type: 'increment'
}
interface Decrement {
type: 'decrement'
}
type Action = Increment | Decrement
const inc: Increment = { type: 'increment' };
const dec: Decrement = { type: 'decrement' };
//this would be a typescript variation
const actionMap = Object.freeze({
[inc.type]: n => n + 1,
[dec.type]: n => n-1
});
function doAction(action: Action, val: number): number {
if(actionMap[action.type]) {
return actionMap[action.type](val);
}
//this would error at compile time if the above checked failed
const _exhaustiveCheck: never = action;
}
console.log(doAction(inc, 1));
console.log(doAction(dec, 1));
只是要清楚。您想检查actionMap是否有区别联合Action中所有'type'值的值。它是否正确? –
是的!那就对了 :) – davidkomer