Is it possible in Typescript to assign a type to a variable using a constant declaration?

My desired outcome (This does not conform to TS rules) :

const type1 = "number";
let myVariable1 : typeof<type1> = 12;
let type2 = "string" as const;
let myVariable2 : typeof<type2> = "foo";

Is it possible to implement a type in TypeScript like this?

Answer №1

To implement a certain type based on a specific string input, you can utilize a conditional type structure like this:

type TypeByString<T> = T extends "number" ? number : T extends "string" ? string : any;

type strType = TypeByString<"string">; // strType now represents string
type numType = TypeByString<"number">; // numType is now of number type

Answer №2

This concept was inspired by Sebastian Speitel's response :

An alternative approach is to incorporate type checking with a custom type :

type Person = { name : string, age : number };

type CustomType<T> = T extends "Person" ? Person : number;

const x: CustomType<"Person"> = {name : "Bar", age: 25};
const y: CustomType<"other"> = 30;

It is also feasible to extract string types from an array of strings :

type CustomExtract<T> = T extends 'number' ? number : T extends 'string' ? string : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'number[]' ? number[] : T extends 'string[]' ? string[] : T extends 'boolean[]' ? boolean[] : any;

const mySelections = ["string", "null"] as const;
const chosen = mySelections[0];
const e : CustomExtract<typeof chosen> = "awesome";
const f : CustomExtract<typeof mySelections[1]> = null;

Answer №3

In my opinion, a straightforward approach to support this concept is by establishing an interface that connects your type names with actual types. By doing so, you can easily retrieve them:

interface LookupType {
  number: number
  string: string
  boolean: boolean
  "number[]": number[]
  person: Person
}

const type1 = "number";
let myVariable1: LookupType[typeof type1] = 12;

let type2 = "string" as const;
let myVariable2: LookupType[typeof type2] = "foo";

let type3 = 'number[]' as const
let myVariable3: LookupType[typeof type3] = [1,2,3]

This strategy functions effectively because the keys within this interface are strings, regardless of whether that string aligns with the name of the referenced type. This method proves to be simpler to maintain compared to using multiple conditional statements.


Furthermore, it offers the advantage of facilitating straightforward type checking for unsupported types

let doesntExist = 'badTypeName' as const
let badVar: LookupType[typeof doesntExist] = 123
// Property 'badTypeName' does not exist on type 'LookupType'.(2339)

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

Bar chart in Chart.js becomes crowded and illegible on smaller screens due to overlapping bars

Hello there! I've encountered an issue where the bar chart overlaps when the screen width is too low. It seems to be related to the maintainAspectRatio property, which I set to false because I wanted the charts to shrink only in width, not in both axe ...

Is it possible to import node_modules from a specific directory mentioned in the "main" section of the package.json file?

Is it feasible to import from a source other than what is defined by the "main" setting? In my node_modules-installed library, the main file is located at lib/index.js With es2015 imports (source generated from ts compiled js), I can use the following ...

"Combining HTML, PHP, and JavaScript for Dynamic Web

Here is the PHP function that retrieves the visitor's profile image thumbnail: <?php echo voip_profile_image($visitorid,'thumb'); ?> The issue lies in the fact that $visitorid is stored in JavaScript under the sRemoteid parameter. Wi ...

Is there a way to customize the color of the like button?

I'm trying to create a Twitter-like button with an icon that changes color. When the button is clicked, it successfully changes from gray to red. But now I'm stuck on how to make it switch back from red to gray. I am currently using javascript ...

Angular $resource failing to transfer parameter to Express endpoint

I am currently working on an Angular application that needs to retrieve data from a MongoDB collection. To accomplish this, I am utilizing the $resource service within the flConstruct. The "query" function works well as it returns all data from the server ...

Initiating a conversation using a greeting in the Javascript bot framework

I am looking to initiate a multi-level, multiple choice dialog from the welcome message in the Bot Framework SDK using JavaScript. I have a main dialog (finalAnswerDialog) that utilizes LUIS for predicting intents, and a multi-level, multiple choice menu d ...

What causes the namespace to shift when utilizing npm for installing a library?

I've been attempting to integrate whammy.js into a project. The initial line in the source code is window.Whammy = (function(){ yet, after running npm i and inspecting node_modules, I discovered global.Whammy = (function(){ https://github.com/anti ...

What is the reason for updating only one out of three charts using react-chartjs-2?

Recently, I came across an issue with a modal that includes a text field for recording numerical values. These recorded values are then passed through a loop to populate an array based on the input. Subsequently, these values get updated in 3 different gra ...

The issue at hand is that the headers cannot be redefined once they have already been sent

Hello, I have tried numerous solutions but have not been able to resolve the "Can't set headers after they are sent" error in the following simple code. I have spent several days working on this and would greatly appreciate any input you may have. ap ...

Tips for executing a function only once within the animation loop in Three.js

Is there a way to call a function only once when a certain condition is met in Three.js? I am currently sampling the frames per second (FPS) to send it to an external service. The FPS is sampled and averaged over time, and the average value is sent after 1 ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

Attempting to loop through a JSON data structure in a React component

Trying to add a toggle checkbox for each JSON value present. Here is an example of the json object pertaining to element { "sourceIP": { "Primary": ["237.100.100.3", "238.0.4.8"], "Secondary": ["237.0.1.178", "237.1.1.91"] }, " ...

Tips for changing a function signature from an external TypeScript library

Is it possible to replace the function signature of an external package with custom types? Imagine using an external package called translationpackage and wanting to utilize its translate function. The original function signature from the package is: // ...

Difficulty arises when trying to deploy a React application on a stationary Nginx server

I'm encountering issues trying to deploy my React app on a remote server. My Nginx configuration looks like this: server { listen 80; listen [::]:80; server_name xxx.xxx.x.x; root /var/www/my-site; inde ...

Ever wonder what goes on behind the scenes when you press a button before the Javascript method is carried out

My web application is built using ASP.NET MVC 4, jQuery, and Telerik's Kendo controls. Within my webpage, I have the following code snippet: <input id="cmdSaveToFile" title="Save To File" class="button" type="button" value="Save To File" onclick= ...

How to Use Discord.js v13 to Make an Announcement in a Specific Channel

Looking for a Solution I am trying to create a command that allows an admin user to send a specific message to a designated channel. The Issue at Hand My current approach involves sending a response back to the user who triggered the command with the ent ...

Implementing the linking of a URL to an HTML hidden button that is dynamically displayed through a Javascript program

I'm currently developing a basic webpage that has a feature allowing users to download the final result as an image file in the last step. To achieve this, I've added a hidden HTML button for downloading the result image and used CSS to set its ...

What is the best practice for inserting typescript definitions and writing them when the object already has a pre-existing definition?

Apologies for this question, as I am struggling to find the necessary information due to my limited understanding of Typescript. I have integrated a jquery plugin called typeahead and added a global variable named bound on the window object for communicati ...

To extract three records from storage and store them in the dbResult using a promise join technique

How can I efficiently retrieve and store 3 records in dbResult using promise join? Currently, I have code that retrieves a single record as shown below: req.oracleMobile.storage.getById(registry.getIncidentPhotoStorageName(), incident_id + '_01&apos ...

How can GraphQL facilitate JOIN requests instead of multiple sequential requests?

I am working with two GraphQL types: type Author { id: String! name: String! } type Book { id: String! author: Author! name: String! } In my database structure, I have set up a foreign key relationship within the books table: table authors (e ...