简体   繁体   English

关于打字稿接口定义

[英]About typescript interface definition

I have a function A which will return function B. The param of function B is object C. C has a property called D whose type is T.我有一个函数 A,它将返回函数 B。函数 B 的参数是对象 C。C 有一个名为 D 的属性,其类型为 T。

The T is decided when I get B which means I could set T when I call A or some other ways. T 是在我得到 B 时决定的,这意味着我可以在我调用 A 或其他方式时设置 T。

So how to define it in typescript?那么如何在打字稿中定义它呢? Thanks so much.非常感谢。


I've tried this which will work.我试过这个会起作用。 But that's not what I want:但这不是我想要的:

interface C<T> {
    d: T;
    e: number;
}

interface B<T> {
    (param: C<T>): void;
}

interface A<T> {
    (): B<T>;
}

const a: A<number> = () => ({d, e}) => {
    console.log(d, e)
};

The things I want maybe something like:我想要的东西可能是这样的:

const a: A = () => ({d, e}) => {
    console.log(d, e)
};
const b1 = a<number>();
const b2 = a<string>();

I have no idea about this.我不知道这个。

You are on the right path, I find it cleaner with types rather than interfaces :你走在正确的道路上,我发现类型而不是接口更清晰:

interface C<T> {
    d: T;
    e: number;
}

type B<T> = (params: C<T>) => void

type A = <T>() => B<T>

// or inlined : type A = <T>() => (params: C<T>) => void

const a: A = () => ({d, e}) => {
    console.log(d, e)
};

const withNumber = a<number>();
const withString = a<string>();

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

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