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

Non-Destructive Type Assertion #422

Closed
cyberixae opened this issue Feb 18, 2020 · 3 comments
Closed

Non-Destructive Type Assertion #422

cyberixae opened this issue Feb 18, 2020 · 3 comments

Comments

@cyberixae
Copy link
Sponsor

🚀 Feature request

Current Behavior

Consider the following type and decoder.

const Named = t.type({
  name: t.string,
});
type Named = t.TypeOf<typeof Named>;

The codec is only interested in whether or not it's input has a name.
Using the type directly would disallow other fields from being included.

const cat: Named = {
  name: 'Findus',
  born: 1984,  // this is an error
};

While using decode would introduce an unnecessary Either.

const cat = Named.decode({
  name: 'Findus',
  born: 1984,
});
// cat now has an Either type

Desired Behavior

Being able to assert compliance without introducing an Either would be convenient.

const cat = Named.assert({
  name: 'Findus',
  born: 1984,
});

Suggested Solution

I imagine assert could be part of the Decoder interface.

export type Assert<A> = <I extends A>(i: I) => I

export interface Decoder<I, A> {
  readonly name: string
  readonly validate: Validate<I, A>
  readonly decode: Decode<I, A>
  readonly assert: Assert<A>
}

Describe alternatives you've considered

Using an IIFE works but is a bit verbose.

const cat = (<C extends Named>(c: C) => c)({
  name: 'Findus',
  born: 1984,
});
@gcanti
Copy link
Owner

gcanti commented Feb 18, 2020

@cyberixae not sure I'm following, looks like a workaround for a TypeScript feature rather than something related to io-ts

@cyberixae
Copy link
Sponsor Author

You are right. It is a convenience feature. And it could be made obsolete by introducing a similar convenience feature to TypeScript. I started a Stack Overflow thread to gather more information of the current situation. https://stackoverflow.com/questions/60298695/non-destructive-type-assertions-in-typescript/60298919

@cyberixae
Copy link
Sponsor Author

I started working on my own convenience wrapper and added this feature in the wrapper as assert. https://www.npmjs.com/package/io-ts-validator

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