我正在做一个打字项目,我遇到了一个似乎无法解决的打字错误.以下是代码的简化版本:
type OptionMode = 'A' | 'B' | 'C';
const Foo = <Mode extends OptionMode>(
mode: Mode
): Mode extends 'A' ? string : number => {
// Your implementation here
// Example implementation:
if (mode === 'A') {
return 'This is a string';// ERROR: Type 'string' is not assignable to type 'Mode extends "A" ? string : number'.(2322)
} else {
return 1 // ERROR:Type 'number' is not assignable to type 'Mode extends "A" ? string : number'.(2322)
}
};
const stringResult = Foo( 'A');
const numberResult= Foo( 'B');
在这段代码中,我try 创建一个foo函数,它根据输入模式返回一个字符串或一个数字.但是,我收到以下错误:
-
Type 'string' is not assignable to type 'Mode extends "A" ? string : number'.(2322)
个 -
Type 'number' is not assignable to type 'Mode extends "A" ? string : number'.(2322)
个
我很难理解为什么会发生这些错误,以及如何修复它们.有没有人能帮我弄清楚哪里出了问题,以及如何让这段代码按预期工作?
谢谢!