【问题标题】:Constraining generic function arguments to generic interface type将泛型函数参数约束为泛型接口类型
【发布时间】:2020-09-16 03:18:09
【问题描述】:

在 Typescript 中,我有一个通用接口,表示我想传递给函数的类型。

//foo must be an object {}, not a number or string or boolean or array
interface MyInterface<T extends {[key: string]: any}> {
  foo: T
}

所以我将我的函数设为通用但 TS 不会从我的界面推断约束

const myGenericFn: <T, U extends MyInterface<T>>(bar: U) => void = (bar) => {
  //Why is T not constrained to {[key: string]: any}? 
  //Shouldn't the constraint be inferred from MyInterface<T>?
  // Or be an error since T doesn't extend {[key: string]: any}?


  //bar.foo is T but T does not extend {[key: string]: any}! 
  const baz = bar.foo

}

//No error! Should be constrained to {foo: {[key: string]: any}} but accepts {foo: string}!
myGenericFn({foo: "bar"})

我认为使这项工作的唯一方法是像这样重复对 T 的约束

const myGenericFnNotDRY: <T extends {[key: string]: any}, U extends MyInterface<T>>(bar: U) => void = (bar) => {
  //Not DRY, I have to repeat my generic constraint everywhere I want to use MyInterface within a generic fn!

  //bar.foo now correctly extends {[key: string]: any}
  const baz = bar.foo
}

//Errors as expected, string not assignable to {[key: string]: any}
myGenericFnNotDRY({foo: "bar"})

这似乎是 TS 中的一个很大的漏洞——它在不告诉我的情况下默默地放弃了类型约束。这很容易导致非常难以跟踪错误。我可能在这里遗漏了一些基本概念。

TS Playground for above code

为什么 TS 不从 MyInterface 推断出对 T 的约束?如何键入我的函数以使 T 正确地约束到 MyInterface 上的特定约束?

【问题讨论】:

  • 很奇怪。 A simpler case is here. 它推断 MyInterface&lt;string&gt; 没有错误,但如果你明确地这样做是不允许的。

标签: typescript typescript-generics


【解决方案1】:

我建议做以下两件事之一:

// Solution 1: use conditional types to make sure you can never pass a "foo"
// that is not a Record<string, unknown>
interface MyInterface1<T> {
  foo: T extends Record<string, unknown> ? T : never;
}

const myGenericFn1: <T>(bar: MyInterface1<T>) => void = (bar) => {
  // ...
}

// Yaaaay! Error! I mean shit
myGenericFn1({ foo: "bar" });

// No error here though, just to check
myGenericFn1({ foo: { something: "somewhere" } });

// Solution 2: Use type parameter constraint using unknown rather than any
// 
// This solution though has the same drawback you didn't like in your original
// post - you need to repeat the constraint in front of your function
interface MyInterface2<T extends Record<string, unknown>> {
  foo: T;
}

const myGenericFn2: <T extends Record<string, unknown>>(bar: MyInterface2<T>) => void = (bar) => {
  // ...
}

// Yaaaay! Error! I mean shit
myGenericFn2({ foo: "bar" });

// No error here though, just to check
myGenericFn1({ foo: { something: "somewhere" } });

TypeScript 游乐场是here。

【讨论】:

  • 您能解释一下为什么我的原始版本不起作用吗?我不明白为什么 TS 允许“T”在 myGenericFn 上不受约束——它似乎只是忽略了 MyInterface 上的约束
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多