| 12 | * Union type, such as string | number |
| 13 | */ |
| 14 | export class UnionType implements Type<any> { |
| 15 | constructor(public itemTypes: Type<any>[]) {} |
| 16 | |
| 17 | readonly name = 'union'; |
| 18 | |
| 19 | isInstance(value: any) { |
| 20 | return this.itemTypes.some(t => t.isInstance(value)); |
| 21 | } |
| 22 | |
| 23 | isCoercible(value: any) { |
| 24 | return this.itemTypes.some(t => t.isCoercible(value)); |
| 25 | } |
| 26 | |
| 27 | defaultValue() { |
| 28 | return this.itemTypes[0].defaultValue(); |
| 29 | } |
| 30 | |
| 31 | coerce(value: any) { |
| 32 | // First find instances |
| 33 | for (const type of this.itemTypes) { |
| 34 | if (type.isInstance(value)) { |
| 35 | return type.coerce(value); |
| 36 | } |
| 37 | } |
| 38 | // Try coercible |
| 39 | for (const type of this.itemTypes) { |
| 40 | if (type.isCoercible(value)) { |
| 41 | return type.coerce(value); |
| 42 | } |
| 43 | } |
| 44 | const msg = util.format('Invalid %s: %j', this.name, value); |
| 45 | throw new TypeError(msg); |
| 46 | } |
| 47 | |
| 48 | serialize(value: any) { |
| 49 | for (const type of this.itemTypes) { |
| 50 | if (type.isInstance(value)) { |
| 51 | return type.serialize(value); |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | } |
nothing calls this directly
no outgoing calls
no test coverage detected