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

Proposal: GlobalConstructor #249

Closed
remcohaszing opened this issue Aug 18, 2021 · 4 comments
Closed

Proposal: GlobalConstructor #249

remcohaszing opened this issue Aug 18, 2021 · 4 comments

Comments

@remcohaszing
Copy link

Sometimes it’s useful to get a property which may or may not exist on a type.

A practical example is that many libraries support both NodeJS buffers and a browser environment. If these libraries depend on the Buffer type, they need to pull in @types/node. However, this is undesirable for a browser environment. This helper type could resolve the issue like this:

// This is the same as `Buffer` in a Node environment, but `never` in a browser environment.
type Buffer = GlobalConstructor<'Buffer'>
@sindresorhus
Copy link
Owner

What does the code for GlobalConstructor look like? It's hard to evaluate the proposal without seeing how it might work.

@remcohaszing
Copy link
Author

I’m not sure what it should look like. I can think of specific implementations, but not of a reusable one as I proposed here.

Perhaps it’s better to just expose some types with quirky behaviour between NodeJS and the dom lib.

// Buffer if @types/node is included
// never if @types/node is not included
export type Buffer = typeof globalThis extends {Buffer: {from: (string: any) => infer T}} ? T : never

Unfortunately if this is processed by TypeScript when generating a .d.ts file from a .ts file, it’s normalized to either Buffer or never.

@voxpelli
Copy link
Collaborator

Currently this module has no types which interacts with the global types in any way.

The README points to https://github.com/g-plane/typed-query-selector for document.querySelector and document.querySelectorAll

I think this is best handled in a similar way, keeping this module's focus strictly on utility types in the spirit of https://www.typescriptlang.org/docs/handbook/utility-types.html

@sindresorhus
Copy link
Owner

I agree with @voxpelli. I also think it's a problem the TypeScript project should fix. I would recommend opening an issue there about it: https://github.com/microsoft/TypeScript

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

3 participants