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: add type guard keyIn #47

Open
tychenjiajun opened this issue Mar 18, 2022 · 7 comments
Open

Proposal: add type guard keyIn #47

tychenjiajun opened this issue Mar 18, 2022 · 7 comments
Labels
enhancement New feature or request help wanted Extra attention is needed

Comments

@tychenjiajun
Copy link
Contributor

tychenjiajun commented Mar 18, 2022

Usage

const a = 'foo';

const obj = {
    foo: 1
}

if (keyIn(a, obj)) {
    // a is literal type 'foo' now
}

Playground


See microsoft/TypeScript#43284

Also, see microsoft/TypeScript#21732 I think our objectHasOwn has partially done the job.

@sindresorhus
Copy link
Owner

I think our objectHasOwn has partially done the job.

By "partially", do you mean that it only gets the "own" keys and you want any key?

Maybe we should name the utility objectHas?

@younho9
Copy link
Contributor

younho9 commented Mar 20, 2022

By "partially", do you mean that it only gets the "own" keys and you want any key?

Additionally objectHasOwn guards that a "property's existence", but does not infer the "type of property".

Is there a need to improve objectHasOwn to infer the type of property as well?

@sindresorhus
Copy link
Owner

Additionally objectHasOwn guards that a "property's existence", but does not infer the "type of property".

How would it infer the "type of property" if that info not already there?

@sindresorhus
Copy link
Owner

Is there a need to improve objectHasOwn to infer the type of property as well?

I'm always happy to make any of the methods more strongly-typed whenever possible.

@younho9
Copy link
Contributor

younho9 commented Mar 20, 2022

How would it infer the "type of property" if that info not already there?

It seems impossible yet. I guess he described it as "partially" for this reason.

@tychenjiajun
Copy link
Contributor Author

Let's limit the discussion to microsoft/TypeScript#43284 , I'll open a new issue for microsoft/TypeScript#21732

@sindresorhus
Copy link
Owner

I'm ok with adding keyIn. But the docs should be clear about the differences it and the normal key in object and with objectHasOwn.

@sindresorhus sindresorhus added enhancement New feature or request help wanted Extra attention is needed labels Mar 22, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

3 participants