Search code examples
typescriptobjectcastingkeyhasownproperty

check if object has key in Typescript and use that key


I have the following code:

let show = {
    createTag: false,
    updateFeature: false,
    createFeatureGroup: false,
    deleteFeature: false,
    deleteCycle: false,
};

And I'm getting a value from the querystring that I want to match agains the keys of show.

The following code works ok, but I want a way to let Typescrpt infer it and avoid having to issue the cast:

const showDialog = $page.query.get('show') || '';

if (showDialog && showDialog in show) {
    // I want to get rid of the "<keyof typeof show>" cast
    show[<keyof typeof show>showDialog] = true; 
}

I though that just issueing showDialog in show typescript would know that inside that if showDialog is a key of show, but it doesn't seem to be the case.


Solution

  • You can create a type guard:

    function isValidParam(k: string): k is keyof typeof show {
      return k in show;
    }
    
    const showDialog = $page.query.get('show') || '';
    
    if (isValidParam(showDialog)) {
        show[showDialog] = true; 
    }
    

    but you decide if it's worth it. I'd probably just keep the cast, personally.