4 ms·
This is a neat trick especially if your brain got rewired to think about union and disjoint types. I recently had to do something like this to force separatuon
by illiarian 4y ago
This is a neat trick especially if your brain got rewired to think about union and disjoint types. I recently had to do something like this to force separatuon of required arams that go into a media control wrapper:
type ControlParams = { type: 'audio' } & ControlParamsAudio | { type: 'video } & ControlParamsVideo
const ControlsWRapper : React.FC<ControlParams> = <>....</>
Boom, you have proper autocomplete and typechecks for audio controls or for video controls depending on your type.
- dimaaan 4y agoSimilar trick for JSON-based web API's that returns either error message or result async fetchApi<TResult = void>(request: Request): Promise<TResult> { type SuccessfulApiResponse = { Succeeded: true; Result: TResult } type FailedApiResponse = { Succeeded: false; Error: string | null | undefined } type ApiResponse = SuccessfulApiResponse | FailedApiResponse; const response = await fetch(request); ensureStatusOK(response); const result = await response.json() as ApiResponse if (!result.Succeeded) throw new Error(result.Error || 'Unknown API error'); return result.Result }