In my TypeScript code, I am working with a type called NameValue and another one called MixedStuff.
type NameValue = { name: string; value: string };
type MixedStuff = NameValue | string;
function stripTwoChars(stuffs: MixedStuff[]): string {
let stuffZero = stuffs[0];
return (typeof stuffZero === "string" ?
stuffZero.slice(0, 2) :
stuffZero.name.slice(0, 2)); // This works fine
return (typeof stuffs[0] === "string" ?
stuffs[0].slice(0, 2) : // Here error: no slice on NameValue
stuffs[0].name.slice(0, 2)); // Here error: no name on string
}
In the function, I first assign the first item in the list to a variable and then perform a typeof check on it, which functions as expected.
However, when I directly perform the typeof check on the first element of the list, it does not work correctly.
I am curious to know if this behavior is intentional or if there could be a bug causing this inconsistency.