-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
indexing optional attributes fails when indexing with a key that is keyof interface #52895
Comments
Duplicate of #10530. Type narrowing does not occur for indexed access forms |
That works, thanks! interface foo {
bar?: number
}
function baz(
qux: foo,
field_: keyof foo
): void {
const field = field_;
if (qux[field] !== undefined) {
console.log(qux[field] + 1)
}
} |
This does not work if there are multiple optional fields: interface foo {
bar1?: number
bar2?: number
}
function baz(
qux: foo,
field_: keyof foo
): void {
const field = field_;
if (qux[field] !== undefined) {
console.log(qux[field] + 1)
}
} same error, "Object is possibly 'undefined'" |
Oh, you were probably talking about storing interface foo {
bar1?: number
bar2?: number
}
function baz(
qux: foo,
field: keyof foo
): void {
const blub = qux[field];
if (blub !== undefined) {
console.log(blub + 1)
}
} |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
π Search Terms
π Version & Regression Information
keyof
β― Playground Link
https://www.typescriptlang.org/play?ts=5.0.0-dev.20230221#code/JYOwLgpgTgZghgYwgAhgezcg3gWAFDKHIBGcUA-AFzIgCuAtsdPgL774y0gJjBogk4ALwAU+IsgCOtAB7V0aADTiiMYBAA2AE2oBrCAE80MVBnwBKagDc0wLdhWFgJkdJkBtNZq0BdZAEIAXkDkLi0INRAILXMHAgkiBH4AZzQNCAA6DTQAc1dZT3VtPwBqZABGc0dkNjxaoA
π» Code
π Actual behavior
Object is possibly 'undefined'
errorπ Expected behavior
To work just like if
field
is set to'bar'
instead ofkeyof foo
The text was updated successfully, but these errors were encountered: