Skip to content
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

Add isObject #253

Closed
fregante opened this issue Aug 25, 2021 · 2 comments
Closed

Add isObject #253

fregante opened this issue Aug 25, 2021 · 2 comments

Comments

@fregante
Copy link

fregante commented Aug 25, 2021

Type guards are hard:

interface Message {
	text: string;
}
function isMessage(value: unknown): value is Message {
  return value !== null && typeof value === 'object' && typeof value.type === 'string';
}

On the surface this is pretty straightforward and how you'd normally do type guards in any language, but:

error TS2531: Object is possibly 'null'.

19   return value !== null && typeof value === 'object' && typeof value.type === 'string';
                                                                  ~~~~~

TS2339: Property 'type' does not exist on type 'object'.

19   return value !== null && typeof value === 'object' && typeof value.type === 'string';
                                                                        ~~~~

Fun facts:

  1. Moving the null check after the 'object' type check, fixes the first error, even if that shouldn't change anything.
  2. If you use an intermediary Record<string, unknown> type, you can access that type without errors
interface Message {
	text: string;
}

function isObject(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null;
}

function isMessage(value: unknown): value is Message {
  return isObject(value) && typeof value["type"] === 'string';
}

I think this isObject type guard is necessary in every type guard until TypeScript decides that object is actually Record<string, unknown> | null like one would expect.

Related:

@sindresorhus
Copy link
Owner

What type are you proposing? It sounds like you want: https://github.com/sindresorhus/is#objectvalue

Also, it seems like this will be fixed soon: microsoft/TypeScript#28131 (comment)

@fregante
Copy link
Author

fregante commented Aug 29, 2021

D'oh, you may be right. I'm not proposing a plain type.

However that PR only fixes the check order part, but it doesn't result into a Record type. The result is still an object without properties.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants