The 'keyof T' type does not meet the specified constraint

I am encountering this error even though the validation is functioning correctly. I am in need of a function that can create another function using an object to filter arguments of a specific type.

Type 'keyof T' does not meet the constraint '"a" | "b" | "c"'.
  Type 'string' cannot be assigned to type '"a" | "b" | "c"'.
    Type 'keyof T' cannot be assigned to type '"c"'.
      Type 'string' cannot be assigned to type '"c"'

type GM = {
    a: number;
    b: string;
    c: string
}

type VMeth<T, C > = (old: T, n: C) => any;

const getVF = <T extends { [key in keyof Partial<GM>]: 1 }>(part: T):  VMeth<GM, Pick<GM, keyof T>> => {
    return function(){ } as any
}

const fd = getVF({ a: 1 });

fd({ a: 1, b: "", c: "s"}, { a: 1 });

Playground link

Answer №1

When the constraint

T extends { [key in keyof Partial<GM>]: 1 }

is applied, it means that T must be able to be assigned to {a?:1, b?:1, c?:1}. This not only includes types you intend to support, like {a: 1}, but also types you may not have intended to support. In TypeScript, object types are considered "extendable" or "open", meaning properties can be added to them. Therefore, a type like

{a?: 1, b?:1, c?:1, oops: string}
is also supported:

const oopsie = getVF({ a: 1, oops: "oops" }) // no error!
// const oopsie: VMeth<GM, Pick<GM, "a" | "oops">

This leads to the compiler rightly complaining about the following:

// Type 'keyof T' does not satisfy the constraint 'keyof GM'.

If you want to specifically limit the keys of part to those of GM, you can make your function generic in those keys using K:

const getVF = <K extends keyof GM>(part: Record<K, 1>):
    VMeth<GM, Pick<GM, K>> => {
    return function () { } as any
}

Now, K must be a subset of

"a" | "b" | "c"
and cannot include "oops" or any other unauthorized key. The functionality remains the same for your desired use case:

fd({ a: 1, b: "", c: "s" }, { a: 1 });
// const fd: (old: GM, n: Pick<GM, "a">) => any

You will now receive compiler warnings if an unexpected property is added:

getVF({ a: 1, oops: "oops" }); // error, excess property!

Even though it's still possible to sneak in an excess property by being tricky:

const existingObj = {a: 1, oops: "oops"} as const;
const aliased: {a: 1} = existingObj;
const okay = getVF(aliased); // no error
// const okay: VMeth<GM, Pick<GM, "a">>

At least the resulting value is always Pick<GM, "a"> and not an invalid selection like

Pick<GM, "a" | "oops">
.


Click here to access the code on the TypeScript 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

Exploring Angular Scope within a Typescript-based javascript function

My current setup involves Typescript with Angular combined with Breezejs. class CounterController { count: number = 0; static $inject = ['$scope']; constructor($scope) { $scope.vm = this; } setCount14(): void { ...

Receiving an empty response when fetching JSON data using HTTP protocol

As a newcomer to Angular2, I'm struggling to understand how http requests work in this framework. Despite following tutorials and experimenting with both promises and observables, I can't seem to get the json response to display in my component. ...

Ways to resolve the error "TS2741: The property 'children' is not present"

Encountering an issue with one of my custom elements: https://i.sstatic.net/4EDnZ.png Error TS2741: Type '{ }' is missing property 'children' required in type 'StringChildren' The component in question is Comment export fu ...

Tips on how to export variables that are defined within the .then() function

Hey there! I'm currently working on an Angular application using single spa. Integrating the single spa feature with an existing Angular app involves creating a new main file which is used to start the application. My issue arises when trying to incor ...

Combining AngularJS and Typescript for Enhanced Scope Functionality

I have decided to shift my approach in writing AngularJS apps from plain JavaScript to using TypeScript as a pre-processor. One of my challenges lies in merging the two approaches, particularly when dealing with scoped method calls. Let's take the e ...

What prevents `console.log` from working within a button click event?

Why is this not functioning correctly? <button (click)="console.log('ok');">Display Details</button> The error message reads: Cannot read property 'log' of undefined However, a console.log statement in the class construc ...

What is causing this TypeScript error to be raised by this statement?

Can you explain why the following statement is throwing a type error? const x: Chat = { ...doc.data(), id: doc.id } The error message states: Type '{ id: string; }' is missing the following properties from type 'Chat': message, name, ...

Encountering a CastError while attempting to send a POST request using Postman

I'm encountering a CastError when attempting to send a POST request using Postman. Why am I unable to simply send the patient and provider fields as strings? Should I refer to this documentation for guidance? I've come across some solutions, but ...

Exploring the attributes of a record through a combination of string template types

I'm utilizing a string template type to denote ids with a significant prefix, such as dta-t-${string} where dta-t- encodes certain details about the entity. I have various record types that are indexed by unions of string templates: type ActivityTempl ...

Struggling to create an Extension Method for Map<TKey, TValue[]> in TypeScript

As a new Angular/TypeScript user, I am really enjoying using Extension methods. They work well on standard types, but now I am facing an issue while trying to write one for the Map data structure where values are arrays. Unfortunately, it does not seem to ...

Retrieving an Enum member based on its value in TypeScript

I am working with an enum called ABC: enum ABC { A = 'a', B = 'b', C = 'c', } In addition, I have a method named doSomething: doSomething(enum: ABC) { switch(enum) { case A : console.log(A); break; case ...

Having trouble viewing the initial value in an AngularJS2 inputText field

I'm having trouble displaying the initial value in inputText. I'm unsure of what mistake I'm making, but the value should be showing up as expected. Kind regards, Alper <input type="text" value="1" [(ngModel)]="Input.VSAT_input1" name= ...

The error message indicates that the property `v.context.$implicit` is not callable

I am a beginner with Typescript and it has only been 3 days. I am trying to access data from Firebase and display it in a list. However, I keep encountering an error when trying to navigate to another page using (Click) ="item ()". Can someone point out wh ...

Prisma Remix is throwing a TypeError: "The function (0, import_prisma.createNote) is not defined as a function."

In my project, I wrote a function using the prisma client which is being called from the notes.tsx route in remix. export async function createNote(entity: { title: string, description: string }) { const note = await prisma.note.create({ data: ...

The ASP.NET Core Web API successfully sends back a response, but unfortunately, the frontend is only seeing an empty value along with a status code of 200 (OK)

Currently, I am delving into the world of web APIs and have stumbled upon a perplexing issue that requires assistance. I have an active ASP.NET Core Web API at the backend, while at the frontend, an Angular application (running on version 15.1.5) is in pl ...

What is the type of return from withRouter?

I'm a beginner with TypeScript and React. I'm encountering an error with Eslint that says "Missing return type on function" in my React HOC that uses withRouter. I'm puzzled about how to define the return type for the filterRedirectHOC funct ...

What is the process for incorporating a restriction in a map within a generic framework?

Note: The explanation provided was not clear enough; you might find it helpful to move on to the next example. I'm facing an issue with the constraints on generics and struggling to identify my mistake. Here is the code snippet: Code snippet goe ...

"Error: The property $notify is not found in the type" - Unable to utilize an npm package in Vue application

Currently integrating this npm package for notification functionalities in my Vue application. Despite following the setup instructions and adding necessary implementations in the main.ts, encountering an error message when attempting to utilize its featur ...

Tips on resolving the issue of 'caught local exception thrown' while utilizing instanceof for identifying the type of internal errors

I've encountered a scenario where I'm loading a set of plugins in my code. Each plugin executes a series of functions within a try-catch block to check for failures and handle them accordingly. Some functions within the plugin can return specific ...

Dealing with Errors in a POST Request using Angular

I have been following the instructions provided in the official Angular documentation found at https://angular.io/guide/http. I encountered an issue with the handleError function within the post request, as it requires 2 arguments and is displaying an err ...