Y
Y
yarnstart2020-05-31 00:20:20
typescript
yarnstart, 2020-05-31 00:20:20

Is it possible to set a default value for a function that depends on two generic types?

Working code example:

Working code

const displayFunctionCode = <T, P>(callback: (props: T) => P) => {
    console.log(callback);
}

displayFunctionCode<number, number>((n) => n);


Sample code that I would like to work:
Desired code

const displayFunctionCode = (callback: (props: T) => P = (prop: T) => prop) => {
console.log(callback);
}

displayFunctionCode((n) => n);


Is it possible to make ts believe that the return value in a function is exactly of type P, like ?
(prop: T) => props as P;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-05-31
@yarnstart

There is such a construction: - by double casting you can cast anything into anything. Only here you don’t need to do this, this one kills the whole point of using TypeScript. Instead, you need to write conditions in the "default function" so that it works as it is described, and not the hell understand how. foo as unknown as Type

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question