-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Type elimination and CFA/Type Guards #11557
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
I guess I'm not understanding what additional information is conveyed in a type |
Here is an example - I know that I could write that piece of code in different way (or to use // Just an alias
type UserGuid = string
type FindBy = 'cost' | 'size' | UserId
function getUserInputFromCommandLine():FindBy {
console.log("Write: cost | size | {UserGuid}")
return 'cost' // user input taken from command line
}
const by = getUserInputFromCommandLine()
function findBySpecificKind(kind: 'cost' | 'size') {
}
function findByUserId(userId: UserGuid) {
}
if (by == 'cost' || by == 'size') {
findBySpecificKind(by) // ERROR - string not assignable to 'cost' | 'size'
}
else {
findByUserId(by)
} So I was hoping to improve user experience in 2 ways:
if (by == 'cost' || by == 'size') {
findBySpecificKind(by) // ERROR - string not assignable to 'cost' | 'size', but CFA could figure out that it matched string literals in (non simplified) type definition
} But if you feel like this makes no sense - feel free to close it |
Ok, I think we should investigate is having equality comparison operations narrow from type const by: string = ...
if (by == 'cost' || by == 'size') {
findBySpecificKind(by); // by should narrow to "cost" | "size" here
} This was already proposed in #11306, so I will close this one as a duplicate. |
It probably was discussed in the past - but couldn't find.
so TS (even if its 'working as intended' from compiler point of view) not only eliminated important information for developer that
generateToken
function can return'TokenA' | 'TokenB' | string
but also removed original type nameEncryptedToken
which could be also important for developer to understand the code - leaving user with juststring
so
1a: Could TS keep the type:
'TokenA' | 'TokenB' | string
as'TokenA' | 'TokenB' | string
and not downgrade tostring
?Theoretically equivalent (from user point of view) code:
retains the type
but
does not
1b: Could TS show the original type as well?
Instead of showing type as
string
could it show:type: EncryptedToken
ortype: EncryptedToken = string
(if 1a is not possible) ortype: EncryptedToken = 'TokenA' | 'TokenB' | string
(if 1a possible)Now because of 1a the following code will not work:
But this code will work:EDIT: This code works because enum is pretty much treated as number (#11559):
Problem is that I want to use the same pattern for strings - but there are no enum strings (yet #1206 (comment))
The text was updated successfully, but these errors were encountered: