Can TypeScript be used to define a variable that determines the type of other variables?
I want to simplify the process by only needing to check one variable, stateIndicator
, which is dependent on other variables to infer their types.
type A = {prop1: string}
type B = {prop2: number}
function isA(x: A | B): x is A {
return (x as A).prop1 !== undefined
}
function foo1(data: A | B) {
const stateIndicator = isA(data);
if (stateIndicator) {
// this is fine
const myString: string = data.prop1;
}
}
function foo2(data: A | B) {
const stateIndicator = isA(data) ? "stateA" : "stateB";
if (stateIndicator === "stateA") {
// without checking if isA(data) or using 'data as A', data.prop1 will show error
// Property 'prop1' does not exist on type 'B'
const myString: string = data.prop1;
}
}