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

Exact Object #319

Open
karlhorky opened this issue Sep 24, 2022 · 3 comments
Open

Exact Object #319

karlhorky opened this issue Sep 24, 2022 · 3 comments

Comments

@karlhorky
Copy link

karlhorky commented Sep 24, 2022

🍩 Feature Request

Is your feature request related to a problem?

It would be great to have an exact object / interface utility type as a part of ts-toolbelt - preventing any fewer properties or excess properties passed in an object - such as:

function fn(arg: Exact<{ x: string }>) {}

// ok
fn({ x: '' });

// errors
fn({ y: '' });
fn({ x: '', y: '' });

This is one of the top-requested features in TypeScript itself, but does not yet exist in the language.

Describe the solution you'd like

A new exported Object/Exact utility type to allow for checking against exact types

Describe alternatives you've considered

I saw Function/Exact, but this appears to be something different... This docs page does use some of the same words when describing the problem, which at first seems to indicate it's the right thing:

Force A to comply with W. A must be a shape of W. In other words, A must extend W and have the same properties - no more, no less.

...but I don't understand how / where I would apply this Exact<A, W> generic signature. 🤔

Teachability, Documentation, Adoption, Migration Strategy

For implementation of the utility, some of the answers in the TypeScript issue are potentially useful:

The code block in the first section above could be used an example in the docs for the type.

@karlhorky
Copy link
Author

Ah, looking closer at the implementation + tests of Function/Exact in 57982b9, it looks like it may indeed do what I'm asking for:

import { Exact } from 'ts-toolbelt/out/Function/Exact'

function exactObject<A>(x: Exact<A, {a: number, b: 2}>) {}

// ok
exactObject({} as {a: 1, b: 2})

// errors
exactObject({} as {a: 1, b: 2, c: 3})
exactObject({} as {a: 1})

Playground


Since the tests for Function/Exact didn't include a test case for excess object properties, I opened #320 to add this.


I am happy to receive any more background info about exact types here, but I think this issue can now be closed?

@millsp
Copy link
Owner

millsp commented Sep 28, 2022

Thank you!

@karlhorky
Copy link
Author

Glad to help! Let me know what you think of #320 :)

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