Last active
June 18, 2019 02:00
-
-
Save devdoomari3/7eff4478fe3d3d345af69486440eea07 to your computer and use it in GitHub Desktop.
typescript-string-enums with iots
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as t from 'io-ts' | |
export class FromTsStringEnumType<T extends object> extends t.Type<T[keyof T]> { | |
constructor (public enumObject: T, name?: string) { | |
super( | |
name || `fromTsStringEnum: ${enumObject}`, | |
(u): u is T[keyof T] => Object | |
.values(enumObject) | |
.some(v => v === u), | |
(u, c) => (this.is(u) ? t.success(u) : t.failure(u, c)), | |
t.identity, | |
) | |
} | |
} | |
export function fromTsStringEnum<T extends object> ( | |
enumObject: T, | |
name?: string, | |
): FromTsStringEnumType<T> { | |
return new FromTsStringEnumType(enumObject, name) | |
} | |
///////// USAGE EXAMPLE: ///////// | |
import { Enum as tseEnum } from 'typescript-string-enums' | |
const arrEnum = tseEnum( | |
'a', 'b', | |
) | |
type arrEnum = tseEnum<typeof arrEnum> | |
const test = t.type({ | |
enum: fromTsStringEnum(arrEnum), | |
}) | |
type test = t.TypeOf<typeof test> | |
const validateOK1 = test | |
.decode({ | |
enum: 'c', | |
}) | |
.isLeft() | |
console.log('validateOK1', validateOK1) | |
const validateOK2 = test | |
.decode({ | |
enum: arrEnum.b, | |
}) | |
.isLeft() | |
console.log('validateOK2', validateOK2) | |
function testaaa (a: test) { | |
if (a.enum === arrEnum.a) { | |
return false | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment