Linking a string value to a specific data structure in TypeScript

I'm currently exploring typescript and I have a question about mapping a string value to a custom type when using templates in function calls.

For instance:

object.method<TypeMapper['CustomType']>([...])

In this scenario, 'CustomType' could be a personalized interface like:

interface CustomType {
x: number,
y: number
}

and the resulting javascript code would look like:

object.method<CustomType>([...])

This is my current code:

interface CustomType {
  x: number,
  y: number
}

interface TypeMapper { 'CustomType': CustomType }

type Test = TypeMapper['CustomType'] // CustomType

function func<T>(x: number, y: number) {
  let v: T;
}
const typeVariable = 'CustomType';
const z = func<TypeMapper[typeVariable]>(1,2);
// 'typeVariable' refers to a value, but is being used as a type here.
// Did you mean 'typeof typeVariable'?(2749)

Answer №1

The error message is a helpful hint on how to resolve the issue:

'typeVariable' is referencing a value but is being used as a type in this context. Did you mean 'typeof typeVariable'?(2749)

In TypeScript, the type system cannot directly operate on values. To address this, you must convert a value to its corresponding type using the typeof keyword.

const typeVariable = 'CustomType';
type Z = TypeMapper[typeof typeVariable] // equivalent to: type Z = CustomType

If you hover over func in this line

const z = func<TypeMapper[typeof typeVariable]>(1,2);

You should see that it has the following type:

function func<CustomType>(x: number, y: number): void

This appears to be the desired outcome based on your code.

Playground


I am utilizing a dynamic string variable that is not known at compile time

This presents a challenge because types are only defined during compile time. If the string's value is unknown until runtime, you will need to handle it dynamically.

Consider the following function:

function func1(type_string: string) {
  type t = TypeMapper[typeof type_string];
}

You can pass any arbitrary string into this function, as indicated by its type definition. What would you expect t to be if you pass in "BadString"?

To make this scenario work, you must narrow down the type string to specific types for safe usage detection.

For instance:

function func1(type_string: string) {
  if (type_string === 'CustomType') {
    type t = TypeMapper[typeof type_string]; // valid operation
  } else {
    throw new Error(`Unknown type string: ${type_string}`)
  }
}

Playground

There are multiple techniques for narrowing types, but without more context from your code snippet, it's challenging to recommend a specific approach.

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

Utilizing Service within Express Router

My journey into the world of NodeJS is just beginning, coming from a .NET background with a love for dependency injection, inversion of control, and microservices. I am now venturing into TypeScript to create services based on my past experiences. Using ex ...

Top Recommendations: Comparing Standalone Components and Modules in Angular Version 14

I'm in need of some clarification on the most effective practices when it comes to utilizing standalone components and modules within Angular 14. With the introduction of standalone components as a new concept in Angular, I am seeking factual guidance ...

Is a shallow copy created by spreading?

According to the example provided in the documentation, let first:number[] = [1, 2]; let second:number[] = [3, 4]; let both_plus:number[] = [0, ...first, ...second, 5]; console.log(`both_plus is ${both_plus}`); first[0] = 20; console.log(`first is ${firs ...

Transforming this JavaScript function using Template Strings into TypeScript

Is there anyone out there who can assist with the following query? I have a functional .js file that I need to integrate into a TypeScript program. import React from "react"; import styled, { css } from "styled-components"; const style = ({ theme, ...res ...

Next.js production build encountering an infinite loading error

I have been utilizing the Next.js TypeScript starter from https://github.com/jpedroschmitz/typescript-nextjs-starter for my current project. The issue I am facing is that when I attempt to build the project after creating numerous components and files, it ...

Oops! The API request was denied with error code 401 - Unauthorized in React

I have been working on incorporating an API into my front-end project using React/Typescript. The documentation for the API specifies that authorization requires a key named token with a corresponding value, which should be included in the header. To stor ...

How can one specify a type in Typescript with a precise number of properties with unspecified names?

Imagine I have a variable with a name and a value, both of which I need for a specific task such as logging. This can be achieved in the following way: const some_variable = "abcdef" const another_variable = 12345 const log1 = (name: string, value: any) ...

What is the best way to showcase column data in a React table when the data within the column is an array of objects?

Utilizing a react table to showcase a data table. In the tags column, the goal is to display all tags present in the tags array of objects. Despite several attempts, no success has been achieved yet. Being new to working with tables, any guidance on a more ...

Is it possible to display Angular Material Slider after the label?

Searching through the Angular Material docks, I came across the Sliders feature. By default, the slider is displayed first, followed by its label like this: https://i.sstatic.net/C5LDj.png However, my goal is to have the text 'Auto Approve?' sh ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

Dispatching an asynchronous function error in React with TypeScript and Redux - the parameter type is not assignable to AnyAction

Currently, I am in the process of developing a web application that utilizes Firebase as its database, along with Redux and TypeScript for state management. Within my code, I have a dispatch function nested inside a callback function like so: export const ...

Challenges encountered when using Tailwindcss and Nextjs with class and variables

Hey there, I'm currently facing a major issue with tailwindcss + nextjs... The problem lies in setting classes using a variable. Although the class is defined in the css, tailwind fails to convert it into a style. This is how I need it to be: https ...

Running unit tests using Typescript (excluding AngularJs) can be accomplished by incorporating Jasmine and Webpack

While there is an abundance of resources on how to unit test with Webpack and Jasmine for Angular projects, I am working on a project that utilizes 'plain' TypeScript instead of AngularJs. I have TypeScript classes in my project but do not use c ...

Out-of-order calling of React hooks detected

It's puzzling that the useMemo hook appears to be running before the useEffect hook directly above it. The reason for my suspicion is the error message I'm encountering: TypeError: Cannot read property 'timestamp' of undefined This ...

The CSS scale property is not working as expected when used in a React.js application, specifically

working environment ・next.js ・react ・typescript https://www.youtube.com/watch?v=ujlpzTyJp-M A Toolchip was developed based on the referenced video. However, the --scale: 1; property is not being applied. import React, { FunctionComponent ...

Querying Cloud Firestore with User ID

I'm facing an issue with retrieving a subset of data based on the first letter of the name and including the UID of the document. No matter what I try, it just returns empty data. fetchDataByFirstLetter(firstLetter: string) { this.afs.collection(&a ...

What is the purpose of the 'unique' keyword in TypeScript?

While coding in the TypeScript playground, I stumbled upon a situation where the term unique seems to be reserved. However, I haven't been able to find any official documentation regarding this. https://i.stack.imgur.com/eQq5b.png Does anyone know i ...

Error: Unable to retrieve the value of 'secret' as it is undefined when attempting to assign a response cookie in Express framework

Today's operation that I've carried out countless times seems to be going awry. For some reason, I am unable to set a refresh token cookie using Express. Here is the error message in full /home/me/Code/apGymBE/node_modules/express/lib/response.j ...

Using TypeScript to specify data types in the Vue data object

I am currently utilizing Vue.js with Typescript in a webpack project. Following the guidelines provided in the Recommended Configuration in my tsconfig.json, I have set: "strict": true, Within one of my components, I have: declare interface P ...

Issue encountered when importing a font in TypeScript due to an error in the link tag's crossorigin

How do I troubleshoot a TypeScript error when importing a custom font, such as a Google font? <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> Below is the specific error message: Type 'boolean' is ...