HenriDev
HenriDev

Reputation: 697

how can i make have the specific type infered based on argument passed

I'd like to make it so that my get widget function result automatically returns the specific type based on the parameter I pass to the function. Is there a way to do this in typescript? As of right now it gives me one of the possible types as return but not the specific one corresponding to the key provided.

example

export interface ExampleAccountCenterHTMLElement extends HTMLElement {
    x: () => void;
}

export interface ExampleMiniFooterHTMLElement extends HTMLElement {
    y: () => void;
}

enum ExampleHtmlElementsName {
    ExampleMiniFooter = 'Example-mini-footer',
    ExampleAccountCenter = 'Example-account-center',
}

interface ExampleHtmlElements {
    [ExampleHtmlElementsName.ExampleAccountCenter]: ExampleAccountCenterHTMLElement,
    [ExampleHtmlElementsName.ExampleMiniFooter]: ExampleMiniFooterHTMLElement,
}

export function getWidget(tagName: ExampleHtmlElementsName) {
    return document.querySelector<ExampleHtmlElements[typeof tagName]>(tagName);
}

const res = getWidget(ExampleHtmlElementsName.ExampleAccountCenter)

Upvotes: 1

Views: 38

Answers (1)

Tobias S.
Tobias S.

Reputation: 23925

Using typeof on tagName is not a good idea. You gave tagName the explicit type ExampleHtmlElementsName, and that is excactly what typeof tagName will evaluate to. Instead, make the function generic.

export function getWidget<T extends ExampleHtmlElementsName>(tagName: T) {
    return document.querySelector<ExampleHtmlElements[T]>(tagName);
}

Playground

Upvotes: 2

Related Questions