Last active
November 30, 2023 14:00
-
-
Save michaelevensen/93fb4672579e042934f0c6e7bb8a8fda to your computer and use it in GitHub Desktop.
Really nice flexible way of defining types.
This file contains 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
type QueueItem<T> = | |
| { status: 'idle'; } | |
| { status: 'uploading'; progress: number; } | |
| { status: 'done'; url: string; file: T; } | |
| { status: 'error'; error: Error; }; | |
type QueueItem = { | |
id: number; | |
} & (QueueItemUpload | QueueItemDone | QueueItemError); | |
type QueueItemUpload = { | |
id: number; | |
status: 'pending' | 'uploading'; | |
progress: number; | |
} | |
type QueueItemDone = { | |
id: number; | |
status: 'done'; | |
url: string; // download url | |
file: File; | |
} | |
type QueueItemError = { | |
id: number; | |
status: 'error'; | |
error: Error; | |
} | |
const queue: QueueItem<File>[] = [{ | |
status: 'idle' | |
}, { | |
status: 'uploading', | |
progress: 0 | |
}, { | |
status: 'done', | |
url: 'https://www.google.com', | |
file: new File([], 'test') | |
}, { | |
status: 'error', | |
error: new Error('test') | |
}] | |
// can be checked like this | |
for (const item of queue) { | |
switch (item.status) { | |
case 'uploading': | |
console.log(item.progress); | |
break; | |
case 'done': | |
console.log(item.url); | |
console.log(item.file); | |
break; | |
case 'error': | |
console.log(item.error.message); | |
default: | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment