-
-
Notifications
You must be signed in to change notification settings - Fork 169
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
Ternary operator optimization RELIES on types, and can cause runtime errors #1569
Comments
(nevermind, I misunderstood the issue) |
I disagree here. You are giving an incorrect type to your object here. If it is ever possible that this key is not here, the object should be typed as In general we will always err on the side of caution and use the non-optimized version, but if you tell the compiler for sure the type of this thing is this, and at runtime it is something else, the problem is in your code, and not in TSTL. |
If we are to accept your approach, then it should be stated clearly in TSTL docs that using Type Assertion ( I remind you that: A developer using TSTL - MUST ACKNOWLEDGE that Type Assertion may have runtime effects. I just want to remind here , that in the case I presented above, the runtime error was not due to the "wrong" type being asserted on |
So you would want x to be |
from a high level, it kind of makes sense that the Lua output would depend on what the types are. take a simple example:
thus, the compiler would have to use the types in order to create coherent output. |
In the Array vs Object case, it is a matter of correctness. My approach would be to keep to a minimum the dependency of the transpiling on the types, and thus, like TypeScript, the developer can be SURE that changing types will not have any run-time implications. I cases like Arrays vs Objects, it might be a necessity. But optimizations are not necessary. |
It is kind of hard to document this behavior, Does this sound right? Avoid Type Assertions"Due to some optimizations which depend on type correctness, you should keep in mind that using Type Assertions may have an effect on transpiled code, and can in some cause unexpected behavior. We recommend that you don't use Type Assertions" You may even want to prevent Type Assertions completely, by using ESLint with a rule such as: {
"rules": {
"@typescript-eslint/consistent-type-assertions": ["error", {
"assertionStyle": "never"
}]
}
} |
Consider:
This gets a
ts7053
error sincesomeObj
has no property of namesomeObj.nonExistingKey
.But if we add a type to
someObj
that says it does havenonExistingKey
, like soThen the Ternary operator optimization will transpile it to:
Which causes
x
to have the value5
instead ofundefined
Instead, the code should be keeping non-optimized:
Type Assertion is legitimate typing tool when writing functions that generically handle different data types.
I suggest this optimization should be disabled.
The text was updated successfully, but these errors were encountered: