简体   繁体   English

打字稿传播通用类型约束

[英]Typescript Propagating Generic Type Constraints

Given a generic type: 给定一个通用类型:

export interface Mappable<Type, Src> {
    map: <T = Type, D = Src>(f: (a: Src) => D) => T;
}
export type ComposeMapper<T extends Mappable<A, B>, A, B> = (f: (a: B) => B, m: T) => T;

Why can't I use it in a declaration like so: 我为什么不能在这样的声明中使用它:

// Error: '(' expected
let _cm: <T extends Mappable> ComposeMapper<T>(f, m) => T;

But I can inline the type to declare it like this: 但是我可以内联类型来声明它,如下所示:

const _cm: <T extends Mappable<A ,B>, A, B>(f: (a: B) => B, m: T) => T = (f, m) => m.map(f);

Are generic types in type signatures expected to be right next to the parameter list, and can't be applied to another type? 类型签名中的泛型类型是否应该恰好位于参数列表的旁边,并且不能应用于其他类型?

Your problematic declaration looks like you're trying to create a generic variable , but TypeScript (as of v2.5) doesn't have those. 您有问题的声明看起来像您正在尝试创建一个泛型变量 ,但是TypeScript(从v2.5开始)没有这些。 TypeScript has generic types , which is what ComposeMapper<T> is, and it has generic functions , which is what your last _cm declaration is. TypeScript具有泛型类型 (即ComposeMapper<T>是什么),并且具有泛型函数 (即您最后的_cm声明是什么)。

I'm confused about your typings though, anyway. 无论如何,我还是对您的打字感到困惑。 Mappable is an interface with a generic function map() that returns any type T that the caller of map() specifies? Mappable是具有泛型函数map()的接口,该接口返回map()调用者指定的任何类型T How would that be implemented? 如何实施? And the generic variable you want seems to return the value T , which is only a type , so that would be a syntax error anyway. 而且您想要的通用变量似乎返回 T ,它只是一个类型 ,因此无论如何都是语法错误。 And the last line, where you are calling m.map(f) where m is a T and it returns a T ? 最后一行,您要调用m.map(f) ,其中mT ,它返回T How would you implement that? 您将如何实施? I am very confused and I expect that you are also. 我很困惑,我希望你也是。 My only recommendation is for you to flesh out what you're trying to do and maybe implement it in JavaScript without types, and then see if you can use TypeScript to annotate it. 我唯一的建议是让您充实正在尝试的工作,并可能在不带类型的JavaScript中实现它,然后查看是否可以使用TypeScript对其进行注释。 Or, possibly, spend more time reading the generics section of the handbook ? 或者,可能花更多的时间阅读手册的泛型部分 Not sure. 不确定。

Anyway, hope that helps; 无论如何,希望能有所帮助; good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM