我正在尝试设置一个泛型类型,它将接受2个参数并返回一个函数。
第一个参数-返回函数的单个参数的类型
第二个参数-如果dev希望返回的函数参数是必需的,则需要获取true。
瓦尔被推断为字符串但它仍然认为它不是字符串
任何帮助都将不胜感激
连接至Playground
// Mandatory = true for required parameters
export type ValidationFunction<T = unknown, IsMandatory = unknown> =
<Val = IsMandatory extends true ? T : T | undefined>(val: Val) => true | string;
const test: ValidationFunction<string, true> = (val) => { // error!
// ~~~~
// Type 'Val' is not assignable to type 'string | true'.
return val;
};
test('poop')
// Maybe the core of the issue but weirdly it accepts
// any type of parameter I'll pass to it
test(555)
test(true)
test(null)
test({})
2条答案
按热度按时间qv7cva1a1#
无效答案:
在我看来,你是说你的
ValidationFunction
出于某种原因总是想返回string | true
-为什么?我就这么做
第一个
有效答案:
@jcalz在OP问题的评论中回答。
eimct9ow2#
问题在于,您将
ValidationFunction<T, M>
本身设置为generic function,它带有一个默认值为IsMandatory extends true ? T : T | undefined
的类型参数Val
,但看起来您根本不想让它成为泛型,即使您想让它成为泛型,类型参数Val
也只是 * 默认 * 为某个值;所以test
接受并返回一个完全不受约束的Val
,它可能与string
有关系,也可能没有关系。如果将默认值更改为约束,则会按您希望的方式开始工作:
但是,你并不真的希望它是通用的,我们只需要用它的约束替换
Val
,事情就可以按照你想要的那样继续工作了:Playground代码链接