Skip to content

Instantly share code, notes, and snippets.

@t81lal
Created August 8, 2019 01:28
Show Gist options
  • Save t81lal/dda96041cc2cced8e408314a698b4fa0 to your computer and use it in GitHub Desktop.
Save t81lal/dda96041cc2cced8e408314a698b4fa0 to your computer and use it in GitHub Desktop.
Two different ways to provide runtime type support for the username field
import * as t from 'io-ts';
import { withMessage } from 'io-ts-types/lib/withMessage';
import { Either, either } from 'fp-ts/lib/Either';
interface UsernameBrand {
readonly Username: unique symbol;
}
type ErrorOrString = Either<t.Errors, string>
export const Username2 = new t.Type<string, string, unknown>(
'Username2',
t.string.is,
( u, c ): ErrorOrString =>
either.chain( t.string.validate( u, c ), ( s: string ): ErrorOrString => {
const length = s.length;
if( length <= 2 || length >= 16 ) {
return t.failure( u, c, 'Invalid length' );
} else if( !/^[a-z0-9]+$/i.test( s ) ) {
return t.failure( u, c, 'Invalid characters' );
} else {
return t.success( s );
}
} ),
String
);
export const Username = withMessage( t.brand(
t.string,
( s ): s is t.Branded<string, UsernameBrand> => {
const length = s.length;
if( length <= 2 || length >= 16 ) {
return false;
} else {
return /^[a-z0-9]+$/i.test( s );
}
},
'Username',
), ( x ): string => 'Invalid username' );
export type Username = t.TypeOf<typeof Username>
export type Username2 = t.TypeOf<typeof Username2>
export const LoginRequest = t.type( {
username: Username2,
password: t.string,
} );
export type LoginRequest = t.TypeOf<typeof LoginRequest>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment