Closed
Description
TypeScript Version: 2.8.0-dev.20180222
Search Terms:
assignable type guards
assignable type guard return value
assign type guard to variable
Code
interface A {
type: 'A';
aProperty: string;
}
interface B {
type: 'B';
bProperty: number;
}
type AorB = A | B;
function isA(obj: AorB): obj is A {
return obj.type === 'A';
}
const o = { type: 'A', aProperty: 'value' } as any as AorB;
// this should be an error, and it is
console.log(o.aProperty);
// this should work, and it does
if (isA(o)) {
console.log(o.aProperty);
}
// this example discards the type guard information, but it
// ought to set oIsA to type (o is A), and apply the type
// guard inside the if statement.
const oIsA = isA(o);
if (oIsA) {
console.log(o.aProperty);
}
Expected behavior:
oIsA
should have the type returned by the type guard function. if (oIsA)
... should narrow the type of o
within the if block.
Actual behavior:
oIsA
is a regular boolean value. The type guard function can only be used directly within a conditional block.
Playground Link:
https://goo.gl/6Pk5vr
Related Issues: