Why isn't TypeScript giving an error?

So I'm helping this person on another server and their code looks like the following:
type Unit = {
unit: string;
abbreviation: string;
contains: string[];
};

const units: Unit[] = [{
unit: "ounce",
abbreviation: "oz",
contains: ["ounce", "oz"]
}];

const getUnitAbbreviation = (ingredient: string) => {
const filteredUnits = units.filter(({contains}) => contains.filter((cont) => ingredient.includes(cont)).length > 0)
const sortedUnits = filteredUnits.sort((a, b) => b.unit.split(" ").length - a.unit.split(" ").length)
const zeroth = sortedUnits[0];
const abbv = zeroth.abbreviation;
return abbv;
};

const shouldWork = getUnitAbbreviation("1 ounce of idk");
console.log("shouldWork", shouldWork);
const shouldFail = getUnitAbbreviation("1 idk of idk");
console.log("shouldFail", shouldFail);
type Unit = {
unit: string;
abbreviation: string;
contains: string[];
};

const units: Unit[] = [{
unit: "ounce",
abbreviation: "oz",
contains: ["ounce", "oz"]
}];

const getUnitAbbreviation = (ingredient: string) => {
const filteredUnits = units.filter(({contains}) => contains.filter((cont) => ingredient.includes(cont)).length > 0)
const sortedUnits = filteredUnits.sort((a, b) => b.unit.split(" ").length - a.unit.split(" ").length)
const zeroth = sortedUnits[0];
const abbv = zeroth.abbreviation;
return abbv;
};

const shouldWork = getUnitAbbreviation("1 ounce of idk");
console.log("shouldWork", shouldWork);
const shouldFail = getUnitAbbreviation("1 idk of idk");
console.log("shouldFail", shouldFail);
When you run this, you will get an error of abbreviation isn't defined (for the shouldFail case) It will return undefined if you provide the ? operator zeroth?.abbreviation as expected, but typescript doesn't give a linting error for it Anyone know why?
9 Replies
Kyle
Kyle2y ago
playground
Kyle
Kyle2y ago
code screenshot (no linting error)
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Kyle
Kyle2y ago
ah, that makes sense I figured it was due to the nesting
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Kyle
Kyle2y ago
so why wouldn't it still give a linting error on zeroth.abbreviation like it doesn't have a way of knowing that it isn't, but is also don't have a way of knowing that it is I assume it's just some way that typescript works that I'm sort of missing
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Kyle
Kyle2y ago
Sick thanks
Want results from more Discord servers?
Add your server