Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 937
opensas Avatar asked Nov 22 '25 16:11

opensas


2 Answers

The type guard presented by @paolostyle is very specific to the show object. The following snippet is more generic and can be used for any key in any object:

export function isKeyOfObject<T extends object>(
  key: string | number | symbol,
  obj: T,
): key is keyof T {
  return key in obj;
}
like image 153
Jasper Kuperus Avatar answered Nov 24 '25 10:11

Jasper Kuperus


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.

like image 36
paolostyle Avatar answered Nov 24 '25 11:11

paolostyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!