Generate a type error if the string does not correspond to the key of the object

How can I trigger a type error in TypeScript 4.4.3 for the incorrect string 'c' below, which is not one of the keys of the object that is passed as the first parameter to the doSomething method?

const doSomething = ({ a, b }: { a: number, b: string }): boolean => {
  return a === 1 || b === 'secret'
}

type SomethingParameterName = keyof Parameters<typeof doSomething>[0]

const orderedParameterNames = [
  'b', 'c', 'a' // why no type error for 'c'?
] as SomethingParameterName[]

Check out this code on TypeScript Playground.

I experimented with const and even tried using 'c' as SomethingParameterName directly, but still couldn't generate a type error. Unfortunately, in this scenario, I have no easy way to retrieve the list of keys from any source other than the function itself.

Answer №1

When using TypeScript, the as TypeName construct acts as a type-cast operation. Since the base type of const strings in a union is string, TypeScript interprets this type-cast as a valid type assertion. To encounter the intended error, it is recommended to specify the type for the variable orderedParameterNames rather than casting the assigned value:

const orderedParameterNames: SomethingParameterName[] = [
  'b', 'c', 'a'
]

By following this approach, an error will be flagged specifically on 'c':

Error TS2322: Type '"c"' is not assignable to type '"a" | "b".

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

Using Bazel, Angular, and SocketIO Version 3 seems to be triggering an error: Uncaught TypeError - XMLHttpRequest is not recognized

Looking to integrate socket.io-client (v3) into my Angular project using Bazel for building and running. Encountering an error in the browser console with the ts_devserver: ERROR Error: Uncaught (in promise): TypeError: XMLHttpRequest is not a constructor ...

Guide to importing OBJ file into three.js using TypeScript

Currently, I am utilizing TypeScript along with three.d.ts obtained from definitely typed. While I have successfully been using THREE.JSONLoader, I am encountering difficulties with implementing an OBJLoader from here in a TypeScript project. It seems th ...

Tips for solving a deliberate circular dependency in an angular provider

If the existing injection token for this provider is available, I want to use it. Otherwise, I will use the specified provider. Below is the code snippet: providers: [ { provide: DesignerRecoveryComponentStore, useFacto ...

searchByTextContentUnderListItemAnchorTag

I would like to utilize the getByRole function for writing my test. However, I am encountering issues when using linkitem or 'link' as the role. It seems that I cannot find the desired element. // encountered error TestingLibraryElementError: The ...

Issue encountered while declaring a variable as a function in TSX

Being new to TS, I encountered an interesting issue. The first code snippet worked without any errors: interface Props { active: boolean error: any // unknown input: any // unknown onActivate: Function onKeyUp: Function onSelect: Function onU ...

Guide to correcting the file path of an external css within the public directory on Express framework

I am facing an issue with loading external CSS files and need some help to fix the path. Despite multiple attempts, I have been unsuccessful so far. Below is my category structure: https://i.stack.imgur.com/sLTcN.png Within the header.ejs file, this is h ...

The expiration date is not considered in JWT authentication using passport-jwt

I have been working on implementing an authentication system using JWT token in Express, utilizing passport-jwt and jsonwebtoken. Everything is functioning correctly at the moment, however, I am facing an issue where the token remains valid even after its ...

React JS state that points to another state value

I am trying to create a component that displays a list of products along with individual list items for each product. However, I keep encountering the following error: TypeError: Cannot read property 'products' of undefined new ProductList src/c ...

Discovering the specific value within an array of various objects through Angular

Within a list of objects, I am specifically looking to extract the name "sample 4" from the second set of objects with an ID of 2. How can this value be retrieved using JavaScript or Angular? {Id: 1, name: sample 1, code: "type", order: 1} {Id: 1, name: ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

PrimeNG Template not showing the form

I have integrated a form into PrimeNG's turbotable to allow users to create a new entry (group) in the table located within the footer. However, the form is not being displayed as expected. Can you help me troubleshoot this issue? <ng-template pTe ...

Issue with Angular 2 Observable not triggering the complete function

I've been experimenting with the hero app tutorial for Angular 2 and currently have this Component set up: import { Component, OnInit } from '@angular/core' import { Subject } from 'rxjs/Subject'; import { Hero } from "./hero"; im ...

What is the purpose of the .default() method being added to the class constructor in transpiled Typescript code

In TypeScript, I have the following code snippet to create an instance of ConnectRoles Middleware in Express: let user = new ConnectRoles(config); The middleware initialization is expected to be a simple call to a constructor. However, after transpiling, ...

Unexpected behavior observed in ng-select when pasting search values

When attempting to update an array of strings acting as the model for an ng-select, the values do not appear correctly in the search box. https://i.sstatic.net/WqdJ6.png The values that are displaying correctly are the ones selected from the dropdown men ...

Struggling to chart out the post response in Angular 7

I am facing an issue while setting up a service on Angular version 7. The problem arises with the res.json() method, throwing an error stating Property 'json' does not exist on type 'Object'. Below is my service's code: import {In ...

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...

Show array elements in Angular framework

I need help with displaying a list that contains three columns: menu, menuItem, and order. The desired display format is to show menu and menuItem ordered by order as follows: Menu 1 : order 200 Menu 2 : order 230 Menu 3 : order 250 Menu item 1 : order 2 ...

Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color. Here's my code: color-variatio ...

Managing errors with the RxJS retry operator

I'm facing an issue with my RxJS code where I need to continuously retry a data request upon failure while also handling the error. Currently, I am using the retry operator for this purpose. However, when attempting to subscribe to the retry operator ...