Deep Dive into TypeScript String Literal Types

Trying to find a solution for implementing TSDocs with a string literal type declaration in TypeScript.

For instance:


type InputType = 
/** Comment should also appear for num1 */
'num1' |
/** Would like the TSDoc to be visible for num2 as well */
'num2'

export const test = (...input: InputType[]) => {
    return input
}

tac('num1')

Wanting to display TSDoc comments for 'num1' & 'num2' in tools like VSCode, but currently not working for 'ma1'.

Any ideas on how to achieve this?

Answer №1

Here's an alternative approach you can take:

  type NumberType = "firstNumber" | "secondNumber";

  /**
   *
   * @param {"firstNumber"} input description for the second number
   */
  function calculate(...input: ["secondNumber", ...string[]]): ["secondNumber"];
  /**
   *
   * @param {"firstNumber"} input description for the first number
   */
  function calculate(...input: ["firstNumber", ...string[]]): ["firstNumber"];
  /**
   *
   * @param {string} input description for a custom number
   */
  function calculate(...input: [string, ...string[]]): ["customNumber"];
  function calculate<T extends NumberType, R extends T[]>(...input: [...R]) {
    return input;
  }


  
  calculate("num8");

https://i.sstatic.net/pBIY7.png

Answer №2

Do you require something similar to this:

/**
 * the TSDoc applies to num1
 */
type A = 'num1';

/**
 * the TSDoc applies to num2
 */
type B = 'num2';

export const test = (...input: (A | B)[]) => {
    return input
}

test('num1');

You may also reference the TypeScript Playground linked here.

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

Switching between nested lists with a button: A simple guide

I have successfully created a nested list with buttons added to each parent <li> element. Here is how the list is structured: $("#pr1").append("<button id='bnt-cat13' class='buttons-filter'>expnd1</button>"); $("#pr ...

The SmoothShading feature of THREE does not alter the geometry

I am having trouble with smooth shading on my model - the polygons are still clearly visible and switching between smooth and flat shading in the three.js inspector isn't making a difference. The OBJ file contains vertex normal data, so I don't t ...

What is the best way to eliminate transition effects in Vue.js when there are changes in the data

My Vue.js 2.x component fetches data from the server in this way. <template> ... <a href="..." v-if="data.status !== 'blind'">Link</a> ... </template> <script> export default { ... data: { retu ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...

Building a multi-page application with ExtJs MVC

I'm new to MVC, especially when it comes to extJs. I want to implement the MVC approach in my project. I came across a tutorial at , which provided an example with only one page. In this example, they used app.js to load extjs views. My question is, w ...

ReactJS and Redux: setting input value using properties

I am utilizing a controlled text field to monitor value changes and enforce case sensitivity for the input. In order to achieve this, I need to access the value property of the component's state. The challenge arises when I try to update this field ...

In Javascript, a variable is being defined by combining a string with another variable through concatenation

Hey, I'm relatively new to working with Javascript and am facing an issue that I believe can be resolved easily with the right syntax. The problem lies in setting a variable (totalRow1) where it needs to be concatenated with a string and another vari ...

The necessary parameters are not provided for [Route: sender] with the [URI: {name}/{code}]. The missing parameters are name and code

I have encountered a problem while using AJAX and I am struggling to find a solution. Routes: web.php Route::get('/{name}/{code}', 'TestController@counter'); Route::post('/{name}/{code}', 'TestController@sender')-&g ...

What is the best way to deactivate certain JavaScript functions on my webpage when accessed through a mobile device?

Is there a way to disable specific JavaScript functions when accessing my website from a mobile device? While I can achieve this using CSS only, certain buttons require JavaScript functionality. Below is the internal JavaScript code: var menuBtn = docume ...

I am endeavoring to send out multiple data requests using a function, ensuring that the code execution occurs only once all the results have been received

After reading through a post on Stack Overflow about handling multiple AJAX calls in a loop (How to take an action when all ajax calls in each loop success?), I was able to come up with a solution. I decided to track the number of requests I needed to make ...

ExpressJS Template Caching System

Encountering issues with template caching in my MEAN app. The navigation bar uses conditional logic to show/hide buttons based on user status. Upon page load, values are null or false until login (views, isLoggedIn). The problem arises post-login - despit ...

I am interested in creating an input range slider using React and TypeScript

This code was used to create a slider functionality import { mainModule } from 'process'; import React, { useState } from 'react'; import styled from 'styled-components'; const DragScaleBar = () => { const [value, setV ...

A variable named "quid" has been set with a value of "x" in the session scope

I am trying to figure out how to set a parameter x in JSTL for a function I have, but when I input values as "x" it returns as a string. JS: function updateValue(x) { <q:set var="quid" value="x" scope="session"/> } HTML ...

Automatically switch to the designated tab depending on the URL

Is it possible to automatically activate a specific tab based on the URL structure if my tabs are configured in this way? I am looking for a solution where a link on www.example1.com/notabs.html will redirect to www.example2.com/tabs.html This particular ...

What is the process for generating a new type that includes the optional keys of another type but makes them mandatory?

Imagine having a type like this: type Properties = { name: string age?: number city?: string } If you only want to create a type with age and city as required fields, you can do it like this: type RequiredFields = RequiredOptional<Propertie ...

Transform the array of objects into different clusters

I am facing a challenge where I have an object returning two arrays of objects from an API. My goal is to transform this data into a new array of objects in order to effectively group the information for the Vue v-select component. For a visual representat ...

How to use AngularJS to collapse various panels with unique content

Hey everyone, I'm working on developing a collapsible panel using Angular. The panel should consist of a header and body to display the content. The desired behavior is that when a button is clicked, the content collapses down, and clicking the same b ...

Transform the ISO 8601 date format into another ISO 8601 format with the help of MomentJS

Can a date format like the following: 2003-09-25T14:00:00.000+1000 or 2003-09-25T14:00:00.000+1100 Be converted to this format? 2003-09-25T14:00:00.000Z Using only MomentJS without any manual intervention. Additionally, I would like to understa ...

The 'in' operand is invalid

I am encountering a JavaScript error: "[object Object]" TypeError: invalid 'in' operand a whenever I attempt to perform an AJAX request using the following code: .data("ui-autocomplete")._renderItem = function( ul, item ) { return $( " ...

What is the best way to pinpoint a specific type from multiple derived class instances when working with an array?

When working inside a .forEach loop, I am encountering an issue with narrowing down a type (the last statement in the snippet below). Within that loop, TypeScript interprets that obj is either of type ObjA | ObjB (since TypeScript created a union of all p ...