Reputation: 1191
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
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
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);
Upvotes: 0