Can you confirm if the return type in GenericType is the outcome of the asynchronous operation performed by the promise?
Actually, in your example, there is no generic type present. All types are specifically defined.
Perhaps what you're looking for is this:
const pr:Promise<Array<Number>> = Promise.resolve([1, 2, 3]);
// The handler here is defined with type Array<Number> -> void
const handler = (arg:Array<Number>): void => { // NOTE: void
console.dir(arg);
}
pr.then(handler);
To demonstrate the importance of type preservation:
// doubleToString has type Number -> String
const doubleToString = (n: Number): String => (n * 2).toString();
const doubledAndStringed: Promise<Array<String>> = pr.then(arr => arr.map(doubleToString));
On the other hand, the following will not work:
const repeatString = (s: String): String => s.repeat(1);
const repeated: Promise<Array<String>> = pr.then(arr => arr.map(repeatString))
If you have a function that returns a Promise based on the type of its argument, that's where you would use a generic type:
const wrap = (x: T): Promise<T> => Promise.resolve(x);
Here, T
represents the generic type, ensuring typescript maintains the exact type of the argument:
const wrappedString: Promise<String> = wrap('hello!');
In this case, wrappedString
will hold that specific type regardless of annotations.