Supperhero
Supperhero

Reputation: 1191

Can Typescript automatically detect the types of function arguments and then use those types in the function?

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.

Upvotes: 1

Views: 1159

Answers (2)

jperl
jperl

Reputation: 5112

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

Upvotes: 4

Titulum
Titulum

Reputation: 11456

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.

Upvotes: 0

Related Questions