1

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.

The T is decided when I get B which means I could set T when I call A or some other ways.

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.

2
  • Please provide some code, what have you tried so far? Commented Mar 31, 2020 at 14:51
  • @bugs Hi. I have appended some code. Commented Mar 31, 2020 at 15:13

1 Answer 1

2

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>();
Sign up to request clarification or add additional context in comments.

3 Comments

Hi. Thanks for your answer. I forgot the type syntax. Thank you. :) But I wanna set T when I call a. I have no idea about this.
Right, I just updated my answer to match what you ask
Coooool! Thank you so much! Seems I mix up the generics for interface with pass generics. Really thanks! I'll take a look at that part in typescript again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.