Typescript -计算泛型类型运行不正常

g6baxovj  于 2022-12-05  发布在  TypeScript
关注(0)|答案(2)|浏览(148)

我正在尝试设置一个泛型类型,它将接受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({})
qv7cva1a

qv7cva1a1#

无效答案:

在我看来,你是说你的ValidationFunction出于某种原因总是想返回string | true-为什么?
我就这么做
第一个

有效答案:

// Mandatory = true for required parameters
export type ValidationFunction<T = unknown, IsMandatory = unknown> =
  (val: IsMandatory extends true ? T : T | undefined) => true | string;

const test: ValidationFunction<string, true> = (val) => {
  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({})

@jcalz在OP问题的评论中回答。

eimct9ow

eimct9ow2#

问题在于,您将ValidationFunction<T, M>本身设置为generic function,它带有一个默认值为IsMandatory extends true ? T : T | undefined的类型参数Val,但看起来您根本不想让它成为泛型,即使您想让它成为泛型,类型参数Val也只是 * 默认 * 为某个值;所以test接受并返回一个完全不受约束的Val,它可能与string有关系,也可能没有关系。
如果将默认值更改为约束,则会按您希望的方式开始工作:

export type ValidationFunction<T = unknown, IsMandatory = unknown> =
  <Val extends IsMandatory extends true ? T : T | undefined>(val: Val) => true | string;
//     ^^^^^^^ <-- constraint, not default

const test: ValidationFunction<string, true> = (val) => {
  return val;
}; // okay

test('💩') // okay
test(555) // error
test(true) // error
test(null) // error
test({}) // error

但是,你并不真的希望它是通用的,我们只需要用它的约束替换Val,事情就可以按照你想要的那样继续工作了:

export type ValidationFunction<T = unknown, IsMandatory = unknown> =
  (val: IsMandatory extends true ? T : T | undefined) => true | string;

const test: ValidationFunction<string, true> = (val) => {
  return val;
}; // okay

test('💩') // okay
test(555) // error
test(true) // error
test(null) // error
test({}) // error

Playground代码链接

相关问题