Unlocking the secret to accessing keys from an unidentified data type in TypeScript

The code snippet above will not compile due to an error with the email protection link.

const foo: unknown = {bar: 'baz'}

if (foo && typeof foo === 'object' && 'bar' in foo) {
  console.log(foo.bar)
}

An error message from TSC is:

Property 'bar' does not exist on type 'object'.

How can one convince tsc that foo can have keys with arbitrary names without having to explicitly cast?

For a working example, check out this playground link. https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZiEAuGBXMBrMIDuYYC8MA3gEYCGATigOQUBeNAvgFAsCWcMAFAiDADIBMKAE8ADgFMQXPoQJEaIUgCtJwKDUHC6VLe3x8AlCRYwYoSCAA2kgHTWQAc16I7FSkZZMgA

Answer №1

If you encounter the type unknown, one possible solution is to cast the object foo as type any or create an interface with bar as a property.

const foo: unknown = {bar: 'baz'};

console.log((foo as any).bar);

Alternatively,

const foo: unknown = {bar: 'baz'};

interface HasBar {
   bar: string;
}

console.log((foo as HasBar).bar);

Answer №2

Explore the concept of user-defined type guards. You can determine if an element belongs to a specific type by using this method:

type Bar = {bar: string};

function isBar(element: unknown): element is Bar  {
  return (element as Bar).bar !== undefined;
}

const foo: unknown = {bar: 'baz'}
if (isBar(foo)) {
  console.log(foo.bar)
}

Visit Playground

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

MUI is designed to only manage either onBlur or onKeyPress, but not both simultaneously

Currently, I am working on a project with TypeScript and Material-UI. My main goal is to handle both the onBlur event and the onEnter key press event for a TextField component. Here's the scenario: I have incorporated this text field into a menu. Whe ...

Issue with React.js code not being detected in TSX file (Visual Studio 2015 Update 1 RC)

Currently, I am utilizing Visual Studio 2015 with update 1 release candidate. Interestingly, I have managed to successfully incorporate React.js code and syntax highlighting within a .JSX file. However, when it comes to a .TSX file, nothing seems to be wor ...

Is there a way to tally up the overall count of digits in a number using TypeScript?

Creating a number variable named temp in TypeScript: temp: number = 0.123; Is there a way to determine the total count of digits in a number (in this case, it's 3)? ...

Should Angular libraries be developed using Typescript or transpiled into JavaScript?

Currently, I am in the process of developing a library that will be available as an Angular module through npm. The library itself has been written using typescript. Everything was functioning perfectly up until Angular version 5.0.0, but after this update ...

Middleware for Redux in Typescript

Converting a JavaScript-written React app to Typescript has been quite the challenge for me. The error messages are complex and difficult to decipher, especially when trying to create a simple middleware. I've spent about 5 hours trying to solve an er ...

Difficulty with setting up Typescript in Visual Studio Code on MacOS Catalina

I'm currently facing an issue that appears to be related to the environment. How can I resolve it? And how do I link the installed TSC to my console? Steps to Recreate: npm install -g typescript was able to successfully install or update [email ...

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 ...

The modal popup will be triggered by various button clicks, each displaying slightly different data within the popup

As a newcomer to Angular 4, I have encountered an interesting challenge. Currently, my code consists of two separate components for two different modals triggered by two different button clicks (Add User and Edit User). However, I now face the requiremen ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...

Having troubles with *ngFor in Angular 8? Learn how to use ng-template effectively

I need assistance creating a table with dynamically generated columns and using the PrimeNg library for the grid. Despite asking several questions, I have not received any responses. Can someone please help me achieve this? To generate table column heade ...

Utilizing TypeScript with Context API

This is my first time working with Typescript to create a context, and I'm struggling to get it functioning properly. Whenever I try to define interfaces and include them in my value prop, I encounter errors that I can't figure out on my own. Spe ...

Utilizing Regular Expressions as a Key for Object Mapping

Currently, I am facing a challenge in mapping objects with keys for easy retrieval. The issue arises when the key can either be a string or a RegExp. Assigning a string as a key is simple, but setting a regex as a key poses a problem. This is how I typica ...

The pivotal Angular universal service

In my application, I have the need to store global variables that are specific to each user. To achieve this, I created a Service that allows access to these variables from any component. However, I am wondering if there is a way to share this service t ...

Typescript error: The property 'set' is not found on type '{}'

Below is the code snippet from my store.tsx file: let store = {}; const globalStore = {}; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export d ...

Encountering an issue while trying to integrate custom commands using the addCommand function in WebDriverIO

When using the addCommand function to add a new command, I encountered an error message that states: [ts] Property 'WaitForElementsAmount' does not exist on type 'Client<void>'. Here is an example of the code snippet I used: br ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Unpacking data types from an array of classes in TypeScript: A step-by-step guide

I am working on a function that takes an array or rest of Typescript classes as input and resolves, returning their instances. However, I'm struggling to ensure correct typing for it. If I take one class as an example: class Base { isBase = true ...

What is the best way to retrieve a property value from an object using the .find() method?

I've encountered a problem with the following code snippet in my function: let packName: string = respPack.find(a => {a.id == 'name_input'}).answer.replace(/ /,'_'); My goal is to locate an object by matching its id and retrie ...

Unable to build due to TypeScript Firebase typings not being compatible

This is what I have done: npm install firebase --save typings install npm~firebase --save After executing the above commands, my typings.json file now looks like this: { "ambientDevDependencies": { "angular-protractor": "registry:dt/angular-protract ...