Check out this TypeScript code snippet
type mutable<A,B> = {
mutate: (x : A) => B
}
type maybeMutable<A,B> = {
mutate? : (x : A) => B;
}
const myFunction = function<A,B>(config : A extends B ? maybeMutable<A,B> : mutable<A,B>, argument : A){
let mutate;
if ('mutate' in config) {
mutate = config.mutate;
} else {
mutate = (x : A) => x
}
mutate(argument);
}
The configuration might have the property mutate
or not, depending on the types A and B. If it is present, it must be a function. The code then checks if mutate
is in the config, assigns it if so, or sets the default value otherwise. This default value is the identity function once more. How does TypeScript infer that mutate
can be undefined and thus throws an error
Cannot invoke an object which is possibly 'undefined'
?