I am attempting to utilize a type assertion on an object field within a function and then use the asserted return object.
Here is an example:
interface MyInterface {
abc: string;
}
type Abc = "A" | "B";
function assertAbc(v: string): asserts v is Abc {
if (!["A", "B"].includes(v)) {
throw Error();
}
};
const needAbc = (_: Abc) => true;
const shouldBeWithAbcType = () => {
const myObj: MyInterface = { abc: "A" };
// Everything that comes after this should be an object with abc as type
assertAbc(myObj.abc);
// This works as intended, abc is of type Abc
needAbc(myObj.abc);
// Return the object
return myObj;
}
const c = shouldBeWithAbcType();
// c.abc is a string, so this doesn't work, why ?
needAbc(c.abc);
Why does needAbc(c.abc)
not work?
The TypeScript playground with the example here
The same example, but without the object (returning the Abc type), works though.