-
Notifications
You must be signed in to change notification settings - Fork 12.8k
CFA should consider branch flags #20497
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
Unless there's some simple way to do this that I'm missing, it seems almost incredibly complex to track all the possible interactions of variables as the function runs. |
Maybe you are thinking about a more generic case of taking into consideration all variable assignment types? I was thinking about just :
I detected 3 places in my code that could benefit from this. The workaround I do right now is to define the variable as I think the pattern of using branch flags is quite common. The variable |
Hmm, after thinking about it a bit, a branch flag can have have more values than just two: const enum Animal {
Unknown,
Cow,
Pig,
Chicken,
}
interface IAnimal {
type: Animal;
age: number;
sound: string;
legs: 2 | 4;
}
function detectAnimal(sound: string, age: number): IAnimal {
let type = Animal.Unknown;
let legs: 2 | 4;
if (age > 1) {
if (sound === 'quack quack') {
type = Animal.Chicken;
legs = 2;
}
if (sound === 'nöff nöff') {
type = Animal.Pig;
legs = 4;
}
}
else {
throw new Error('Animals do not make sound at age lower than 1.');
}
if (type !== Animal.Chicken && type !== Animal.Pig) {
legs = 4;
}
return {
type,
age,
sound,
legs, // Error 'legs' is used before assigned.
}
} I could probably put up a more detailed proposal. |
This could be useful for the following cases: const condition = true; // <-- can be obtained differently, the point is that it's a constant
let message: string;
if (condition) message = 'hello';
// Some shared code that runs independently of condition
if (condition) console.log(message); // <--- this gives error "message is not defined"
|
This is a suggestion to improve the CFA. It would be good if TypeScript considered branch flags when analysing code paths.
We assign
text
on all possible code paths above. And it shouldn't error above.A branch flag is simply a boolean variable that is considered when doing the control flow analysis.
The text was updated successfully, but these errors were encountered: