π Search Terms
Optional Chaining, as Operator, Type Narrowing
π Version & Regression Information
v4.6.2, 'Nightly' version as well
β― Playground Link
https://www.typescriptlang.org/play?#code/C4TwDgpgBAkgtgQwObQLxQN4CgpQGYD2ATosAM4BcUZwRAlgHZIDaAumwNxYC+WWokKAAUiBACYBXAMbAo6bLjqIUlWMohsoAHygMJAG31de-cNACCUqRDJliIOZhMCLYsQQaOFUMKMkyqEXFpWR1La1t7bV0DIx4+PAkGGToPKCkACwgpAGsACgQ3D1VzIoY2AEpMHCg6PCg8grKyZgAGVgB+ADpfYJkoBDJhPxCK7qVkG279CCZgDKrvXCli2Tw6Ihp4Sccm9wYW9p6R-sHhvuAKromVNtYuXF5uIA
π» Code
type Image = {
formats: string[][];
}
type Product = {
images: Image[] | null;
}
type Accessory = {}
type Addon = {
product: Product | Accessory | null;
}
function check(addons: Addon[]) {
if ((addons[0]?.product as Product)?.images?.length) {
const firstImage = (addons[0].product as Product).images[0];
}
}
π Actual behavior
Errors in code: Object is possibly 'null'
π Expected behavior
No errors
Additional note
If you remove 'Accessory' type at all and remove the 'as' operator, everything will work fine
π Search Terms
Optional Chaining, as Operator, Type Narrowing
π Version & Regression Information
v4.6.2, 'Nightly' version as well
β― Playground Link
https://www.typescriptlang.org/play?#code/C4TwDgpgBAkgtgQwObQLxQN4CgpQGYD2ATosAM4BcUZwRAlgHZIDaAumwNxYC+WWokKAAUiBACYBXAMbAo6bLjqIUlWMohsoAHygMJAG31de-cNACCUqRDJliIOZhMCLYsQQaOFUMKMkyqEXFpWR1La1t7bV0DIx4+PAkGGToPKCkACwgpAGsACgQ3D1VzIoY2AEpMHCg6PCg8grKyZgAGVgB+ADpfYJkoBDJhPxCK7qVkG279CCZgDKrvXCli2Tw6Ihp4Sccm9wYW9p6R-sHhvuAKromVNtYuXF5uIA
π» Code
π Actual behavior
Errors in code: Object is possibly 'null'
π Expected behavior
No errors
Additional note
If you remove 'Accessory' type at all and remove the 'as' operator, everything will work fine