TypeScript requires that the `includes` function must have the same type parameter for both input and

When working with TypeScript, I've encountered an interesting dilemma regarding the use of the Array.Prototype.includes function. It seems that this function requires me to pass in the same type as in the original array, but isn't the purpose of using includes to determine if a key of arbitrary string type exists in an array with a known type?

Let's consider the following code snippet:

type CONFIG_MODEL = {
  URL: string;
  Protocol: string;
  Port: number;
  Encrypted: boolean;
}

const ALLOWED_KEYS: (keyof CONFIG_MODEL)[] = ['URL', 'Protocol'];

function setup(configs: { [key: string]: string }) {
  Object.keys(configs).forEach(configKey => {
    if (ALLOWED_KEYS.includes(configKey)) {
      // do something
    }
  })
}

Link to TypeScript Playground

It turns out that TypeScript throws an error when trying to use includes, with the message:

Argument of type 'string' is not assignable to parameter of type 'keyof CONFIG_MODEL'

Any insights or suggestions would be greatly appreciated!

Answer №1

To enhance efficiency, consider looping through only the allowed keys instead of all object keys Here is an example:

type CONFIG_MODEL = {
  URL: string;
  Protocol: string;
  Port: number;
  Encrypted: boolean;
}

type AllowedKeys = Array<keyof CONFIG_MODEL>;

const ALLOWED_KEYS: AllowedKeys = ['URL', 'Protocol'];

const hasProperty=<Obj,Prop extends string>(obj:Obj,prop:Prop):obj is Obj & Record<Prop,string>=>
  Object.prototype.hasOwnProperty.call(obj,prop);

function setup(configs: { [key: string]: string }) {  
  ALLOWED_KEYS.forEach(elem=>{
    if(hasProperty(configs, elem)){
      // process the config
      const result = configs[elem] // valid
    }
  })
}

Answer №2

The as string[] conversion right before the .includes method in the code snippet below effectively handles the issue:

//type defined externally in original code
type ClassicalElement = 'earth' | 'water' | 'wind' | 'fire'; 
const classicalElements = ['earth', 'water', 'wind', 'fire'] as ClassicalElement[];
const isClassicalElement = function(
    possibleElement: string
): possibleElement is ClassicalElement {
    return (classicalElements as string[]).includes(possibleElement);
}

You can test this code snippet on TypeScript Playground using the following links: with and without encountering any errors.

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

What is the syntax for passing a generic type to an anonymous function in a TypeScript TSX file?

The issue lies with the function below, which is causing a failure within a .tsx file: export const enhanceComponent = <T>(Component: React.ComponentType<T>) => (props: any) => ( <customContext.Consumer> {addCustomData => ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

The type of the element is implicitly set to 'any' because the expression 'keyof IMyObj' cannot be used to index the type

Trying to avoid specifying types in TypeScript and setting a value by accessing its key is causing a TypeScript error. Despite looking at multiple StackOverflow posts, I couldn't find a solution. I encountered a similar issue with my code and tried r ...

Interface of TypeScript Undetermined

Currently, I am developing a Demo API Wrapper specifically for Roblox. During the development process, I have come across a certain issue that I would like to address. My aim is to send a request and then return all the data in the manner of an API wrapper ...

Issue with Next.js: Router.push not causing page to refresh

I'm currently developing a next.js page called /page/data/[dataId] (this page is accessed when a user clicks on a link from the page /page/data, where I fetch the list of items through an API). When a user clicks on a button, I make an API call to de ...

How to bring in a class that was exported using `export = uuid` in Typescript

I'm facing a challenge while working with the node_module called uuid-js in TypeScript. After installing both the module and its typings, I am unsure how to properly import the module. Question: What is the correct way to import the module? The func ...

Implementing query parameters in a Deno controller

I developed a couple of APIs for a Deno Proof of Concept. This is the route implementation: const router = new Router() router.get('/posts', getPosts) .get('/posts/:id', getPostsById) In the second route, I successfully retriev ...

Issue: The TypeError reported is due to the absence of any definition for "_co.category.category_type"

I have two models: CategoryTypes and Categories. Each category type contains multiple categories. These are my two models. Categories Model import { Categories } from '../../categories/Mode/Categories' export class CategoryType { _id: strin ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

Error in Typescript: The property 'a' is not defined in the type 'A'

Here is an example of the different types I am working with: type Place = { address: string } type Location = { latLng: string } type User = { name: string } & (Place | Location) When attempting to parse the data using this structure, I enco ...

Exploring the use of global variables in React

Welcome to my React learning journey! I've encountered an issue while trying to access a global variable exposed by a browser extension that I'm using. Initially, I attempted to check for the availability of the variable in the componentDidMount ...

A guide on implementing typescript modules within a Node.js environment

It may sound trivial, but unfortunately I am struggling to utilize a Typescript module called device-detector-js in my Node.js project. I have searched the web for solutions on "How to use typescript modules in Node.js", but all I find is tutorials on "Bu ...

The function is receiving an empty array of objects

This code is for an Ionic app written in typescript: let fileNames: any[] = []; fileNames = this.getFileNames("wildlife"); console.log("file names:", fileNames); this.displayFiles(fileNames); The output shows a strange result, as even though there ar ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Organize items within an array based on dual properties rather than a single one

Here is an array of objects that I would like to group based on certain keys (JSON format): [ { "name": "john", "lastName": "doe", "gender": "male" }, { "name": &qu ...

Is there a way to deactivate a tab when it's active and reactivate it upon clicking another tab in Angular?

<a class="nav-link" routerLink="/books" routerLinkActive="active (click)="bookTabIsClicked()" > Books </a> I am currently teaching myself Angular. I need help with disabling this tab when it is active ...

The KeyValuePair<string, Date> type in Typescript cannot be assigned to the KeyValuePair<number, string> type

I encountered the following issue: An error occurred stating that Type 'KeyValuePair<string, Date>' is not assignable to type 'KeyValuePair<number, string>'. Also, it mentioned that Type 'string' is not assignab ...

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

Angular 4: Utilizing a class with a constructor to create an http Observable model

Within my application, I have a Class model that is defined with a constructor. Here is an example: export class Movie { title: string; posterURL: string; description: string; public constructor(cfg: Partial<Movie>) { Object ...

Utilizing a single component for various purposes with diverse tags in react

I am faced with the challenge of creating two almost identical components, Component A: const ClaimedLabel = ():React.Element => ( <div tw=""> <p tw="">Some Text here</p> <div tw=""> <Icon ...