-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Type narrowing generics/unknown doesn't seem to work with typeof and null check #43997
Comments
Duplicate of #28131. |
The second part of this is. There are two issues i would say, the generic function can be re-ordered to have the same order and will still error. e.g. function func<T>(obj: T): boolean {
// Errors because `hasOwnProperty` doesn't exist on T, doesn't know it is an object
if ((typeof obj === 'object') && obj !== null && obj.hasOwnProperty('xyz')) {
return true;
}
return false;
} |
Otherwise you can pass in this object: |
function func<T>(obj: T): boolean {
if ((typeof obj === 'object') && obj !== null && obj.hasOwnProperty('xyz')) {
return true;
}
return false;
}
func('foo'); // false
func(123); // false
func({xyz: 123}); // true
// etc etc |
See my update. If you don't make And
|
out of interest, why isn't that behaviour the same without generics?
const foo: unknown = {hasOwnProperty: () => "blah"};
if (typeof foo === 'object' && foo !== null && foo.hasOwnProperty('blah')) {
// WORKS
} so why is it any different just because we have a i suppose because |
I don't know about the specifics, you'd need to wait for the TypeScript team or someone else more knowledgable. But your guess sounds like a good one to me. It's similar to this example:
|
There are some weird corner cases here I don't recall that lead to this. It's certainly not desirable. |
Bug Report
π Search Terms
typeof object, null checks, narrowing object, narrow generics
π Version & Regression Information
All
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
The generic function doesn't infer that
obj
must be anobject
of some sort.The first if doesn't infer that
testVariable
can't be null.π Expected behavior
The generic function should infer that
T
is anobject
because we did a null check and checkedtypeof
.Both ifs should infer that
testVariable
can't be null.Notes
Is this just me missing some 'known behaviour' typescript has? the two conditions seem to depend on ordering, maybe thats just a known thing i was unaware of (i.e. by design)?
The text was updated successfully, but these errors were encountered: