为什么TypeScript不抱怨此代码?

时间:2019-12-04 18:07:26

标签: typescript typescript-typings

如果我有以下代码:

interface Context {
  id: number;
}

interface FunctionStep<T> {
  (input?: any): (context: T) => (prevStepOutput?: any) => any;
}

function pipe<T extends Record<string, any>>(callbacks: Array<FunctionStep<T>>) {
  return (context: T) => (...args: any) => {};
}

const context: Context = {
  id: 12,
}

const clean: FunctionStep<number> = () => (context) => () => {}

pipe<Context>(clean())(context);

我希望TypeScript抱怨,因为我在应该期望FunctionStep<number>的地方传递了FunctionStep<Context>。为什么反而一切看起来都正确?

测试沙箱:https://codesandbox.io/s/brave-cookies-k51mb

如果这是预期的行为,我该如何限制传递给FunctionStep的{​​{1}}为正确的pipe类型的

2 个答案:

答案 0 :(得分:0)

FunctionStep<T>需要通用类型,这意味着T可以是任何东西。 因此,调用FunctionStep<Context>不会出错。

如果FunctionStep应该期望有一个Context,则没有理由使用泛型类型,则它应该是一个简单的参数。您也可以使用FunctionStep<T extends X | Y>限制T可以使用。

答案 1 :(得分:0)

经过更多修改并考虑了@ kaya3的建议后,我发现了一种使其按预期方式运行的方法:

interface Context {
  id: number;
}

interface FunctionStep<T> {
  (context: T): (prevStepOutput?: any) => any;
}

function pipe<T extends Record<string, any>>(callbacks: Array<FunctionStep<T>>) {
  return (context: T) => (...args: any) => {};
}

const context: Context = {
  id: 12,
}

const clean = (): FunctionStep<Context> => (context) => () => {}

pipe<Context>(clean())(context);
相关问题