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: InvariantOf #288

Closed
younho9 opened this issue Oct 13, 2021 · 4 comments · Fixed by #352
Closed

Proposal: InvariantOf #288

younho9 opened this issue Oct 13, 2021 · 4 comments · Fixed by #352
Labels
help wanted Extra attention is needed type addition

Comments

@younho9
Copy link
Contributor

younho9 commented Oct 13, 2021

Inspired by InvariantOf.

It could be useful to make object invariant. It is similar opaque type without brand or tag.

import {Opaque} from './opaque';

export type InvariantOf<Type> = Opaque<Type, keyof Type>;

I published this utility type as package, but I wish to add it to this project.

Here are some test cases.

I'm willing to do PR. 😃

@younho9
Copy link
Contributor Author

younho9 commented Oct 19, 2021

Update: use function signature to transform type into a invariant type

declare const tag: unique symbol;

declare type InvariantProp<Type> = (arg: Type) => Type;

declare type InvariantTagged<Type> = {
  readonly [tag]: InvariantProp<Type>;
};

/**
 * Transfrom type to Invariant type
 */
export declare type InvariantOf<Base> = Base & InvariantSignature<Base>;

@sindresorhus
Copy link
Owner

What's the practical use-case? I'm not sure when I would need this.

@younho9
Copy link
Contributor Author

younho9 commented Jan 6, 2022

In structural typing, Object can have more properties at run-time, so Object.keys returning (keyof T)[] is quite dangerous.

microsoft/TypeScript#12253 (comment)

If use invariantOf, because it requires exactly the same type, typescript warn at the type level when the structure of the object changes.

TypeScript Playground

This has a tricky side, but there are rare use cases to accurately distinguish the type according to the structure.

@sindresorhus
Copy link
Owner

This is accepted.

For anyone submitting a pull request for this, it should come with a clear description, use-cases, and a practical example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed type addition
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants