-
Notifications
You must be signed in to change notification settings - Fork 12.7k
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
Wrong narrowing with the in
operator
#53910
Comments
in
keywordin
operator
Duplicate of #34975. The |
Maybe you should use |
Ok, I understand that if I were to use the That being said, how can I , without using Using type PartialType = {foo: string}
type FullType = {foo:string, bar:string, baz: string}
function isFullType(object: FullType | PartialType): object is FullType {
type CorrectPartialType = PartialType & { [K in string]: unknown }
const obj: CorrectPartialType | FullType = object
if (typeof(obj.bar) == 'string' && typeof(obj.baz) == 'string'){
const _:FullType = obj // TYPE ERROR here
return true
}
return false
} |
@AxelHaddad Use discriminated unions instead, it is much more sound than regular unions. That is use the following two types: type PartialType = {isFull: false, foo: string}
type FullType = {isFull: true, foo:string, bar:string, baz: string} and check the value of |
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
It seems that the built-in narrowing via the
in
operator can lead to narrowing mistakes (false positive).🔎 Search Terms
Narrowing,
in
, subtypes, type guards🕗 Version & Regression Information
⏯ Playground Link
💻 Code
🙁 Actual behavior
No typescript error.
🙂 Expected behavior
Typescript should not think that
object
is of typeFullType
as for instance all those three following objects, compatible withPartialType
, are clearly notFullType
:Therefore it should raise an error at the line
const _:FullType = object;
.The text was updated successfully, but these errors were encountered: