mirror of
https://github.com/type-challenges/type-challenges.git
synced 2025-12-08 19:06:13 +00:00
Co-authored-by: Anthony Fu <11247099+antfu@users.noreply.github.com>
This commit is contained in:
parent
3c2ea99506
commit
00f824b5bd
18
questions/62-medium-type-lookup/README.md
Normal file
18
questions/62-medium-type-lookup/README.md
Normal 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`
|
||||
```
|
||||
7
questions/62-medium-type-lookup/info.yml
Normal file
7
questions/62-medium-type-lookup/info.yml
Normal file
@ -0,0 +1,7 @@
|
||||
difficulty: medium
|
||||
title: Type Lookup
|
||||
tags: 'union, map'
|
||||
author:
|
||||
github: antfu
|
||||
name: Anthony Fu
|
||||
|
||||
1
questions/62-medium-type-lookup/template.ts
Normal file
1
questions/62-medium-type-lookup/template.ts
Normal file
@ -0,0 +1 @@
|
||||
type LookUp<U, T> = any
|
||||
19
questions/62-medium-type-lookup/test-cases.ts
Normal file
19
questions/62-medium-type-lookup/test-cases.ts
Normal 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>>,
|
||||
]
|
||||
Loading…
x
Reference in New Issue
Block a user