Skip to content

Instantly share code, notes, and snippets.

View metalsadman's full-sized avatar

Aldrin Marquez metalsadman

View GitHub Profile
@IlCallo
IlCallo / injector-factory.ts
Last active January 17, 2022 14:56
Create an injection key and helper function based on a name and an interface describing the injected data. Automatically adds safeguard when the provided data cannot be found
import { inject, InjectionKey, provide } from 'vue';
function getValueFromMaybeFunction<
Args extends unknown[],
Provided,
T = Provided extends (...args: Args) => infer R ? R : Provided
>(params: Args, valueOrFn: Provided): T {
// TS isn't able to narrow down correctly `T | () => T` types as infer `ReturnType<Function>` as any
// See: https://github.com/microsoft/TypeScript/issues/37663
// See: https://github.com/microsoft/TypeScript/issues/37993#issuecomment-615369691