Suppose there are objects with a property called _type_
used to store runtime type information.
interface Foo {
_type_: '<foo>';
thing1: string;
}
interface Bar {
_type_: '<bar>'
thing2: number;
}
function helpme(input: Foo|Bar): string | number {
if (input._type_ === '<foo>') {
return input.thing1;
}
if (input._type_ === '<bar>') {
return input.thing2;
}
return 'N/A';
}
All of this works well and good, but I want to simplify the code by abstracting the _type_
check into a function so that other parts of the code don't need to be aware of this property.
interface Foo {
_type_: '<foo>';
thing1: string;
}
interface Bar {
_type_: '<bar>'
thing2: number;
}
function typeIs(o: any, t: '<foo>' | '<bar>'): o is {_type_: t} {
return o && typeof(o) === 'object' && o._type_ === t;
}
function helpme(input: Foo|Bar): string | number {
if (typeIs(input, '<foo>')) {
return input.thing1;
}
if (typeIs(input, '<bar>')) {
return input.thing2;
}
return 'N/A';
}
However, running this code results in an error:
't' refers to a value, but is being used as a type here. Did you mean 'typeof t'?
This error makes sense. How can I correct the syntax to achieve my goal?