Skip to content

Instantly share code, notes, and snippets.

@michaelevensen
Last active November 30, 2023 14:00
Show Gist options
  • Save michaelevensen/93fb4672579e042934f0c6e7bb8a8fda to your computer and use it in GitHub Desktop.
Save michaelevensen/93fb4672579e042934f0c6e7bb8a8fda to your computer and use it in GitHub Desktop.
Really nice flexible way of defining types.
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