-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Control flow analysis: T|T[] case, Array.isArray and else case #8935
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
Comments
do not think this is accurate. T can be an array.
|
Same thing about non generic functions:
|
@mhegazy Sorry for inconvience, there should be a little more complex case. interface Struct {
type: string
[key: string]: any
}
function handle(object: Struct | Struct []) {
if (Array.isArray(object)) {
for (let single of object) {
handle(single)
}
} else {
Object.keys(object).forEach(key => {
let value = object[key];
if (Array.isArray(value)) {
console.log(value.length);
} else {
console.log(object.type);
}
})
}
} This code raises compilation error on typescript 1.9.0-dev.20160602-1.0 on line
But with typescript 1.8 everything is ok. |
The issue is a change in how narowing works. in TS 1.8 narrowing worked cross function expression/lambda expression, which was not correct; the compiler has no guarantee that if function handle(obj: Struct | Struct []) {
const object = obj; // capture it in a const
if (Array.isArray(object)) {
for (let single of object) {
handle(single)
}
} else {
Object.keys(object).forEach(key => {
let value = object[key];
if (Array.isArray(value)) {
console.log(value.length);
} else {
console.log(object.type);
}
})
}
} You would probably like to get the same behavior for function arguments, except that there is no way to tell the compiler that these are "constant" like variables or "readonly" like members. We have recently discussed allowing a |
TypeScript Version:
1.9.0-dev (nightly)
Code
The text was updated successfully, but these errors were encountered: