Reputation: 323
I am wondering what does the following expression mean (<T = string>() => Promise<T>)
in the following context:
type Src = string | (<T = string>() => Promise<T>);
And used in the following function:
const handleSource = async (source: Src): Promise<void> => {
if (typeof source === 'string') {
setState((s) => ({ ...s, src: source }));
return;
}
try {
const result = await source();
setState((s) => ({ ...s, src: result }));
} catch (e) {
// eslint-disable-next-line no-console
console.warn('[Image] handleSource', e);
setState((s) => ({ ...s, isLoadingError: true }));
}
};
Upvotes: 1
Views: 490
Reputation: 1073968
It means that Src
can either be
T
(which defaults to string
) and returns a promise using that generic parameter to say that if the promise is fulfilled, that's the type the fulfillment value will haveSo for example, you could have a function that looked like this:
function example1(src: Src) {
if (typeof src === "string") {
return src;
}
return src();
}
...that returns a string
or a Promise<string>
, or like this:
function example2(src: Src) {
if (typeof src === "string") {
return src;
}
return src<number>();
}
...that returns a string
or a Promise<number>
(because of the generic type parameter on the call to src
).
Upvotes: 5