1

To explain what I want here's an example. Supposing I have an array shuffle function I want to be able to do this:

type shuffleArray = (someType[])=>someType[]

Where someType isn't declared anywhere but inferred when an argument is passed to the function instead of having to pass the generic type argument in advance like so:

type shuffleArray<T> = (T[])=>T[]

Ideally, I could then use someType on variables inside the body of the function. I don't know if there is a way of doing this and I couldn't find one but it seems like it should be doable.

1

2 Answers 2

4

When using generics, you can either do this:

type MyFunctionType<T> = (param: T) => T[]

and here indeed, you have to manually specify the type each time you use the function, or this:

type MyFunctionType = <T>(param: T) => T[]

and here you let your function INFER what's passed to the function.

More info here: Required vs inferred generic types in TypeScript

Sign up to request clarification or add additional context in comments.

Comments

0

You are trying to use generics without using generics. You should use generics and solve the problem by declaring an interface that contains the methods you want to use:

interface YourType {
  someMethod: () => void;
}

class YourActualType {
    public someMethod() {
        // Do something
    }
}

class AnotherType {
    public someMethod() {
        // Do something else
    }
}

function shuffleArray(values: YourType[]): YourType[] {
    values.forEach(value => value.someMethod());
    return values;
}

const values = [
    new YourActualType(),
    new AnotherType()
];

shuffleArray(values);

Playground link.

Comments

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.