【发布时间】: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 不从 MyInterface 推断出对 T 的约束?如何键入我的函数以使 T 正确地约束到 MyInterface 上的特定约束?
【问题讨论】:
-
很奇怪。 A simpler case is here. 它推断
MyInterface<string>没有错误,但如果你明确地这样做是不允许的。
标签: typescript typescript-generics