feat(question): add #62 - Type Lookup (#63)

Co-authored-by: Anthony Fu <11247099+antfu@users.noreply.github.com>
This commit is contained in:
github-actions[bot] 2020-08-06 20:50:44 +08:00 committed by GitHub
parent 3c2ea99506
commit 00f824b5bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,18 @@
Sometimes, you may want to lookup for a type in a union to by their attributes.
In this challenge, I would like to have get the couponing type by searching for the common `type` field in the union `Cat | Dog`. In other words, I will expect to get `Dog` for `LookUp<Dog | Cat, 'dog'>` and `Cat` for `LookUp<Dog | Cat, 'cat'>` in the following example.
```ts
interface Cat {
type: 'cat'
breeds: 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal'
}
interface Dog {
type: 'dog'
breeds: 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer'
color: 'brown' | 'white' | 'black'
}
const MyDog = LookUp<Cat | Dog, 'dog'> // expected to be `Dog`
```

View File

@ -0,0 +1,7 @@
difficulty: medium
title: Type Lookup
tags: 'union, map'
author:
github: antfu
name: Anthony Fu

View File

@ -0,0 +1 @@
type LookUp<U, T> = any

View File

@ -0,0 +1,19 @@
import { Equal, Expect } from '@type-challenges/utils'
interface Cat {
type: 'cat'
breeds: 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal'
}
interface Dog {
type: 'dog'
breeds: 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer'
color: 'brown' | 'white' | 'black'
}
type Animal = Cat | Dog
type cases = [
Expect<Equal<LookUp<Animal, 'dog'>, Dog>>,
Expect<Equal<LookUp<Animal, 'cat'>, Cat>>,
]