The data type '{ [key: string]: number; }' cannot be assigned to type 'T'

I’m working with a complex TypeScript type and trying to manage it within a function. Here’s what I have:

type T = { a: number } | { b: number }

function func(k: 'a' | 'b', v: number) {
    // error message below
    const t: T = { [k]: v }
    console.log(t);
}

However, I encountered an error:

Type '{ [x: string]: number; }' is not assignable to type 'T'.
  Property 'b' is missing in type '{ [x: string]: number; }' but required in type '{ b: number; }'.

Any ideas on how to resolve this issue?

Answer №1

When setting dynamic keys on its own, the typing is lost, but this can be avoided by defining an explicit type using another function:

function put<K extends PropertyKey, V>(key: K, value: V): {[P in K]: V};
function put<K extends PropertyKey, V>(key: K, value: V) {
  return {[key]: value};
}

Example of usage:

function func(k: "a" | "b", v: number) {
  const t: T = put(k, v); // no error
  console.log(t);
}

Playground Link

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

Typescript is throwing an error with code TS2571, indicating that the object is of type 'unknown'

Hey there, I'm reaching out for assistance in resolving a specific error that has cropped up. try{ } catch { let errMsg; if (error.code === 11000) { errMsg = Object.keys(error.keyValue)[0] + "Already exists"; } return res.status ...

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 ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...

What are the essential requirements for an Angular application to function properly with minimal dependencies?

If a new developer wants to begin learning Angular from scratch, what are the essential npm packages that they need to install in order to start building an Angular application with minimal dependencies? ...

The module 'module://graphql/language/parser.js' could not be resolved

I'm facing an issue while creating a React Native TypeScript project on Snack Expo. Even though I have added graphql to the package.json and included the types file, I keep getting this error : Device: (1:8434) Unable to resolve module 'module:/ ...

How come the type checker is not throwing an error for this indexable type?

I recently delved into the Microsoft Typescript Handbook and found myself intrigued by the indexable types chapter. To gain a deeper understanding, I decided to experiment with the code provided. Strangely enough, upon running this particular piece of code ...

When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files? Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function Check out the TypeScript files below: calculato ...

As a quirk of TypeScript, it does not allow for returning a Tuple directly and instead interprets it as an Array

I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax: export function to(promise:Promise<any>) { return promise .then(data => [null, data]) .catch(err => [ ...

Tips for efficiently utilizing mapActions in vue with Typescript class components!

Can someone please provide guidance on the correct way to use ...mapActions([]) within a Typescript vue class component? This is my current approach: <script lang="ts"> import { Component, Prop, Vue } from "vue-property-decorator"; import { mapActi ...

Unable to refresh the context following a successful API call

My current project in NextJS requires a simple login function, and I have been attempting to implement it using the Context API to store user data. However, I am facing an issue where the context is not updating properly after fetching data from the back-e ...

What is the best way to incorporate auto-completion into a browser-based editor using Monaco?

Recently, I embarked on a project to develop a browser-based editor using monaco and antlr for a unique programming language. Following an excellent guide, I found at , gave me a great start. While Monaco provides basic suggestions with ctrl + space, I am ...

Tips for implementing assertions within the syntax of destructuring?

How can I implement type assertion in destructuring with Typescript? type StringOrNumber = string | number const obj = { foo: 123 as StringOrNumber } const { foo } = obj I've been struggling to find a simple way to apply the number type assertio ...

The TypeScript compiler is unable to locate the name 'window'

Within my Meteor/React project, I encounter the following line of code: let gameId = window.prompt("Please input the ID of the game you would like to load."); The TypeScript compiler presents an error during transpiling: Cannot find name 'window&apo ...

TS2322: Subclass missing property, yet it still exists

In my project, I have defined two Angular 4 component classes. The first class, referred to as the superclass: export class SectionComponent implements OnInit { slides: SlideComponent[]; constructor() { } ngOnInit() { } } And then there&apo ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

The parameter 'any' cannot be assigned to the parameter 'never' - Array provided is incompatible

Currently delving into TypeScript and encountering an issue while setting a reducer in redux Toolkit. Here's the code snippet in question: const testSlice = createSlice({ name: "test", initialState: [], reducers: { callApi: (state, ...

Initialization of an empty array in Typescript

My promises array is structured as follows: export type PromisesArray = [ Promise<IApplicant> | null, Promise<ICampaign | ICampaignLight> | null, Promise<IApplication[]> | null, Promise<IComment[]> | null, Promise<{ st ...

What is the proper way to access the global `angular` variable in Angular and TypeScript when using AngularJS?

I'm currently integrating an Angular 4 component into a large monolithic AngularJS application. The challenge I face lies in the restrictions of the AngularJS project's build system, which limits me to only modifying the project's index.html ...

Displayed even when data is present, the PrimeNg empty message persists

I have set up a PrimeNg table to display data with an empty message template like this: <ng-template pTemplate="emptymessage"> <tr> <td> No records found </td> </tr> </ng-template> ...

The const keyword is not automatically inferred as a const when using conditional types for generic type parameters

Within Typescript, the const modifier can be applied to function type parameters. This ensures that the inferred type matches the literal received with as const. function identity<const T>(a: T){ return a } For example, when using identity({ a: 4 ...