简体   繁体   中英

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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