|
| 1 | +import {expectType} from 'tsd'; |
| 2 | +import type {ExtractStrict} from '../source/extract-strict'; |
| 3 | + |
| 4 | +// Primitive union tests |
| 5 | + |
| 6 | +type ShirtSize = 'xxxl' | 'xxl' | 'xl' | 'l' | 'm' | 's' | 'xs' | 'xxs'; |
| 7 | +type LargeShirtSize = 'xxxl' | 'xxl' | 'xl' | 'l'; |
| 8 | +type SmallShirtSize = 's' | 'xs' | 'xxs'; |
| 9 | + |
| 10 | +declare const largeShirtSizes: ExtractStrict<ShirtSize, LargeShirtSize>; |
| 11 | +expectType<LargeShirtSize>(largeShirtSizes); |
| 12 | + |
| 13 | +declare const smallShirtSizes: ExtractStrict<ShirtSize, SmallShirtSize>; |
| 14 | +expectType<SmallShirtSize>(smallShirtSizes); |
| 15 | + |
| 16 | +// @ts-expect-error |
| 17 | +declare const allInvalidShirtSizes: ExtractStrict<ShirtSize, 'skyscraper-large' | 'atom-small'>; |
| 18 | +expectType<never>(allInvalidShirtSizes); |
| 19 | + |
| 20 | +// @ts-expect-error |
| 21 | +declare const someInvalidShirtSizes: ExtractStrict<ShirtSize, 'm' | 'atom-small'>; |
| 22 | +expectType<'m'>(someInvalidShirtSizes); // This is how native `Extract` works with primitives |
| 23 | + |
| 24 | +// Object union tests |
| 25 | + |
| 26 | +type Foo = { |
| 27 | + kind: 'foo'; |
| 28 | + a: string; |
| 29 | + b: string; |
| 30 | +}; |
| 31 | + |
| 32 | +type Bar = { |
| 33 | + kind: 'bar'; |
| 34 | + a: string; |
| 35 | + b: number; |
| 36 | + c: boolean; |
| 37 | +}; |
| 38 | + |
| 39 | +type Foobar = Foo | Bar; |
| 40 | + |
| 41 | +declare const foobarByA: ExtractStrict<Foobar, {a: string}>; |
| 42 | +expectType<Foobar>(foobarByA); |
| 43 | + |
| 44 | +declare const onlyFooByKind: ExtractStrict<Foobar, {kind: 'foo'}>; |
| 45 | +expectType<Foo>(onlyFooByKind); |
| 46 | + |
| 47 | +declare const onlyFooByB: ExtractStrict<Foobar, {b: string}>; |
| 48 | +expectType<Foo>(onlyFooByB); |
| 49 | + |
| 50 | +declare const onlyBarByC: ExtractStrict<Foobar, {c: boolean}>; |
| 51 | +expectType<Bar>(onlyBarByC); |
| 52 | + |
| 53 | +declare const foobarByUnionBC: ExtractStrict<Foobar, {b: string} | {c: boolean}>; |
| 54 | +expectType<Foobar>(foobarByUnionBC); |
| 55 | + |
| 56 | +// @ts-expect-error |
| 57 | +declare const invalidLoneField: ExtractStrict<Foobar, {d: string}>; |
| 58 | +expectType<never>(invalidLoneField); |
| 59 | + |
| 60 | +// @ts-expect-error |
| 61 | +declare const invalidMixedFields: ExtractStrict<Foobar, {kind: 'foo'; d: string}>; |
| 62 | +expectType<never>(invalidMixedFields); |
| 63 | + |
| 64 | +// @ts-expect-error |
| 65 | +declare const undefinedField: ExtractStrict<Foobar, undefined>; |
| 66 | +expectType<never>(undefinedField); |
0 commit comments