I would like to understand how to get where I want with generic type so this is my example :
function foo(value: 42 = 42 ,bar:(val: any) => any = I => I){
return bar(value)
}
I work with a value
of some type T
in my example the type is a number
so I am using 42
I want to have a function as an argument that will change the value to a different type R
or return a same type T
which in this case would be the identity 'I => I' as the default parameter value.
I rewrote my function as an arrow function like this:
const foo = <R1>(
value: number = 42,
bar: <R0>(val: number) => R0 = I => I
) => {
return bar<R1>(value);
};
const foo0 = (
value: number = 42,
bar: <R0>(val: number) => R0 = I => I
) => {
return bar(value);
};
const foo1 = <R1>(
value: number = 42,
bar: (val: number) => R1 = I => I
) => {
return bar(value);
};
ERROR: Type 'number' is not assignable to type 'RX'.
'RX' could be instantiated with an arbitrary type which could be unrelated to 'number'.
I am using R1
and R0
because I am not sure the difference between R one and R naught in this example but if I remove the I => I
default value the error message go away but I don't understand why or how to overcome it...
in the below example fooB(42,i=>i)
and foo0B(42,i=>i)
erored out but not foo1B(42,i=>i)
How can I set the default value I => I
without having to specify both R | number
const fooB = <R1>(value: number = 42, bar: <R0>(val: number) => R0) => {
return bar<R1>(value);
};
const foo0B = (value: number = 42, bar: <R0>(val: number) => R0) => {
return bar(value);
};
const foo1B = <R1>(value: number = 42, bar: (val: number) => R1) => {
return bar(value);
};
fooB(42,i=>i)
foo0B(42,i=>i)
foo1B(42,i=>i)