Last active
January 23, 2018 21:10
-
-
Save baetheus/f663097b4f02a3b18cb3fa40c62d6606 to your computer and use it in GitHub Desktop.
typeNarrowingProblem1
This file contains hidden or 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
| export enum SomeIds { | |
| ONE = 'one', | |
| TWO = 'two', | |
| } | |
| export enum SomeType { | |
| RED = 'red', | |
| BLUE = 'blue', | |
| } | |
| export interface FieldStructure { | |
| type: SomeType; | |
| data: string; | |
| } | |
| export interface AbstractResponse<T extends SomeIds = SomeIds, F extends string = string> { | |
| id: T; | |
| data: Record<F, FieldStructure>; | |
| } | |
| // ResponseOne | |
| export enum ResponseOneFields { | |
| FIELD_ONE = 'fieldOne', | |
| FIELD_TWO = 'fieldTwo', | |
| FIELD_THREE = 'fieldThree', | |
| } | |
| export interface ResponseOne extends AbstractResponse<SomeIds.ONE, ResponseOneFields> {} | |
| // ResponseTwo | |
| export enum ResponseTwoFields { | |
| JANK = 'jankField', | |
| JUNK = 'junkField', | |
| } | |
| export interface ResponseTwo extends AbstractResponse<SomeIds.TWO, ResponseTwoFields> {} | |
| // Discriminated Union | |
| export type Responses = ResponseOne | ResponseTwo; | |
| function thing(p: Responses) { | |
| switch (p.id) { | |
| case SomeIds.ONE: | |
| return p.data.fieldOne; | |
| case SomeIds.TWO: | |
| return p.data.jankField; | |
| default: | |
| return | |
| } | |
| } | |
| // Now find a way to write the following function with narrowing | |
| function otherThing(p: SomeIds): Responses // When executed have it narrow to ResponseOne or ResponseTwo based on p |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment