Determine if an object contains a specific key in Typescript and access the value associated with that

Here is a snippet of my code:

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

I am retrieving a value from the querystring that I want to compare against the keys in the 'show' object.

The current code works fine, but I would like TypeScript to infer it and avoid the need for casting:

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

if (showDialog && showDialog in show) {
    // I am looking for a way to eliminate the need for "<keyof typeof show>" cast
    show[<keyof typeof show>showDialog] = true; 
}

I initially thought that using showDialog in show inside the 'if' statement would inform TypeScript that showDialog is a key in 'show', but it seems this is not the case.

Answer №1

The solution offered by @paolostyle for type guarding is tailored specifically for the show object. However, the following code snippet provides a more versatile approach that can be applied to any key within any object:

export function validateKeyInObject<T>(
  key: string | number | symbol,
  obj: T,
): key is keyof T {
  return key in obj;
}

Answer №2

If you want to ensure a specific type, consider creating a type guard:

function isValidKey(k: string): k is keyof typeof display {
  return k in display;
}

const displayDialog = $page.query.get('display') || '';

if (isValidKey(displayDialog)) {
    display[displayDialog] = true; 
}

However, whether it's worth the effort is up to you. Personally, I would probably just stick with the cast.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on creating a custom type for an object utilizing an enum framework

Enumerating my shortcuts: export enum Hotkey { MARK_IN = 'markIn', MARK_OUT = 'markOut', GO_TO_MARK_IN = 'goToMarkIn', GO_TO_MARK_OUT = 'goToMarkOut' } I am now looking to define a type for a JSON ob ...

Convert Java object to different object with side effects

for (int i = 0; i < info.size(); i++) { User b = (User) info.get(i); rs = stmt.executeQuery("Select ARTIST,TITLE from SONGS WHERE ID = (SELECT ID from USERS WHERE USERNAME = " + "'" + b.Username + "'" + ")"); ...

Sharing information between a cordova plugin and an Angular application

I have been working on an Angular/Cordova app and I am trying to pass the online/offline status to Angular: export class AppComponent implements OnInit { isOff = false; constructor() { document.addEventListener('deviceready', onDeviceRea ...

Modify the entire WebStorm project to adjust the indentation from 2 spaces to 4 spaces

Is there a method to adjust the indentation of all files within my project simultaneously, rather than having to manually edit each line? When I modify tab and indent spacing settings, it does not affect existing indents and tabs, but instead only applies ...

No response from NgClass after executing the function

In my NgClass function, I make use of an array that is populated in the ngOnInit lifecycle hook. Within ngOnInit, the prepareRezerwation() function creates a variable called colorRezerwation: this.nodeService.getRezerwations(this.minMax).subscribe(re ...

What is the most efficient method for parsing nested objects in AngularJS?

Currently, I am faced with the challenge of utilizing angularjs to parse a complex nested data structure retrieved from a remote server. My main issue lies in accessing the "events" data using the function below: $scope.generate_event = function(){ ...

What factors contribute to the variations in results reported by Eslint on different machines?

We initially utilized tslint in our project but recently made the switch to eslint. When I execute the command "eslint \"packages/**/*.{ts,tsx}\"" on my personal Windows machine, it detects 1 error and 409 warnings. Surprising ...

Adapt the size of HTML video tags based on the width of the screen and level of

Within the site (developed with React, utilizing Typescript and Tailwind), there exists a component that allows users to watch videos (constructed using the HTML Video tag). Additionally, beneath the video, there are various dropdowns and buttons. However, ...

What causes the discrepancy in errors when dealing with subtype versus regular assignments?

Below is a sample code that has been checked by TypeScript playground https://www.typescriptlang.org/play/ interface PartialCustomData { option?: number; } interface A { [key: string]: string | PartialCustomData; } interface B extends A { [k ...

What is the proper way to implement this in a TypeScript constructor?

What is the recommended method for providing a type annotation to this in a constructor? function Client(options: ClientOptions) { const defaultOptions = { host: 'ws://127.0.0.1', port: 8080, logger: function() { ...

What is the method for storing a JSON object path in a variable for use in a template?

Trying to fetch data from a lengthy path has proven challenging for me. I attempted to store the path in a variable and incorporate it into the template, but encountered some issues. Could someone assist me with this? Here is what I have tried: My store ...

Difficulty in toggling the visibility of the react-date-range picker package when selecting a date

I need assistance with a problem I'm facing. I am having trouble hiding and showing the react-date-range picker upon date selection. The issue is related to a package that I am using for date range selection. You can find the package link here - https ...

Only filter the array by its value if the value is specified

Is there a way to apply this filter while only checking each condition if the value is not undefined? For instance, if taxId is undefined, I would like to skip it rather than using it as a filter criterion. this.subAgencies = demoSubAgencies.filter(fun ...

When trying to pass props into setup using VueJS 3 Composition API and TypeScript, an error may occur stating: "Property 'user' does not exist on type"

I need help figuring out why TypeScript is not recognizing that props.user is of type UserInterface. Any advice or guidance would be greatly appreciated. You can reach me at [email protected], [email protected], [email protected]. This seem ...

Testing useEffect with React hooks, Jest, and Enzyme to add and remove event listeners on a ref

Here is a component I've been working on: export const DeviceModule = (props: Props) => { const [isTooltipVisible, changeTooltipVisibility] = useState(false) const deviceRef = useRef(null) useEffect(() => { if (deviceRef && dev ...

Different outputs based on input in Typescript

Looking for some help with my class method. Here is the current implementation: handleTab<B extends boolean = false>(getIndex?: B): B extends true ? number : string { return getIndex ? 1 : ''; } Encountering an error message that s ...

What is the method for defining functions that accept two different object types in Typescript?

After encountering the same issue multiple times, I've decided it's time to address it: How can functions that accept two different object types be defined in Typescript? I've referred to https://www.typescriptlang.org/docs/handbook/unions ...

Is it possible to use a type predicate to return `void` from a function?

When creating data validation APIs, I have a common approach where I include two functions - one that returns a boolean value and another that throws an error. The throwing function typically has a void return type. interface MyType { numberField: num ...

Unable to access data from Service during the OnInit lifecycle hook in Angular 2

In my code, I have a custom WorkingData object that is responsible for passing specific data between components. One of the properties in this object is today, which holds the current date as a Date object. My goal is to continuously update this property e ...

Switching templates based on elementRef width adjustments

I am facing an issue where I am trying to load some data in ngInit and set the width of a div equal to the received data. However, when I try to set some style options in ngAfterViewInit using ViewChild and ElementRef, my elementRef ends up being undefined ...