Description
Bug Report
🔎 Search Terms
type guard object property
🕗 Version & Regression Information
I'm using 4.2.4 in production, I don't know if this bug has occurred in prior versions.
I have tested in the playground that the bug also occurs in 4.3.x and 4.4 beta
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about it.
⏯ Playground Link
Playground link with relevant code
💻 Code
const kTableColumns = ['id', 'title', 'icon'];
type TableData = {
id: string
title: string
icon: string
}
type Metadata = {
url: string
}
type UpdateProps = Partial<Omit<TableData, 'id'>> & Partial<Metadata>;
function update(props: UpdateProps) {
const tableUpdate: Array<{ column: string, value: string }> = [];
kTableColumns.forEach((column) => {
if (typeof props[column as keyof UpdateProps] !== 'undefined') {
// Explicitly checked that props[columns] is not undefined, yet I have to
// use non-null assertion operator to satisfy the compiler.
// Error: string | undefined is not assignable to type string
tableUpdate.push({ column, value: props[column as keyof UpdateProps]}) // Only ! can fix it.
// Besdies this, the `as keyof UpdateProps` should be redundant after
// checking that the value is not undefined.
}
});
}
🙁 Actual behavior
After validating that prop[columns] is not
undefined, the compiler still treats
prop[columns]as possibly
undefined`.
A non-null assertion operator at the end of the value is a workaround, but it feels like it should not be there.
🙂 Expected behavior
The type of prop[columns]
inside the if clause should not be undefined.
Additionally, using column as keyof UpdateProps
should not be required after validating that column is a valid key of the object (though I understand if there are valid reasons against it, I'm mostly concerned about the first issue).