If you need a generic type that can be read as type T
, you can use X extends T
. That means when you read the value you can treat it as T
. E.g.
function foo<X extends number>(x: X) {
console.log(Math.sqrt(x)); // OK because x can be treated as a number when read.
}
How do you do the equivalent for writing to a value?
function foo<X extends number>(x: X) {
x = Math.sqrt(2); // This doesn't work.
}
I want this behaviour:
const a: number | undefined = 5;
const b: string | number = "hello";
const c: string | undefined = "goodbye";
foo(a); // Ok
foo(b); // Ok
foo(c); // Error!