How can we restrict the keys of an object while inferring the values as constant?

Is there a way to set the values of this object as const, while ensuring that the keys are limited to the Field union?

type Field = 'name' | 'isHappy';

const fieldTypes: { [field in Field]: string } = {
  name: 'text',
  isHappy: 'checkbox',
};

I want the type of fieldTypes to be:

{
  name: 'text';
  isHappy: 'checkbox';
}

instead of

{
  name: string;
  isHappy: string;
}

Answer №1

When it comes to variable declarations, there is no room for ambiguity. Variable types in programming are clear-cut, either inferred from the value assigned or explicitly specified through a type annotation.

To navigate this aspect more effectively, one can turn to functions which offer the flexibility of having both inferred and constrained types:

type Field = 'name' | 'isHappy';

function createFields<T extends Record<Field, V>, V extends string>(o: T) {
  return o;
}

const fieldTypes = createFields({
  name: 'text',
  isHappy: 'checkbox',
})

// Resulting in: 
// const fieldTypes: {
//     name: "text";
//     isHappy: "checkbox";
// }

Explore on 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

React progress bar that changes dynamically

Dynamic Progress Bar: state = { progress: 0, } render() { return ( <Progress value={this.state.progress} title="Saving the details"/> ); I am looking for a way to dynamically increase the progress bar over time. Can someone assist me wi ...

Is there a way to turn off the warning overlay in a React application?

I’m currently using react-app-rewired and I am trying to figure out how to turn off the overlay that displays Typescript warnings whenever I compile. It seems like some warnings that are not caught by the VSCode Typescript checker pop up on this overlay ...

The Jasmine tests seem to have a mind of their own,

Encountering a peculiar problem during the execution of my Jasmine tests in the Bamboo build. The tests are failing sporadically with the error message below: Failed: can't convert undefined to object on 18-Nov-2019 at 03:08:56 ./node_modules/@a ...

When using React with TypeScript, there seems to be an issue where using history.push to change the URL results in rendering the 404 page instead

I have gone through all the previous answers but none of them could solve my problem. I am new to React and currently working on a personal project where I use React with TypeScript, Redux, and Material UI. For some reason, when I try to redirect from ins ...

The absence of the 'classes' property in the MUI component type is causing an issue in Typescript Material UI

Simply put, typescript is giving me a hard time by complaining about the missing property classes on every material-ui component. Essentially, Typescript requires the presence of the classes property in nearly all material-ui components. Here is the error ...

What is the reason behind this occurrence in TypeScript? (specifically union types)

I'm confused because I can't find a definite answer to this question: Consider the following type definition: type A = { prop2: string; prop1: string; } | { prop3: string; prop1: string; } This type includes one shared property ...

Create a new TypeScript object without any initial properties, then proceed to define its attributes

Working on honing my skills with Angular Forms utilizing the template-driven approach. My goal is to construct a user interface to display the output of my data in this structure: <hr> <div class="well well-lg"> ...

Ways to extract information from nested arrays

Currently, I am working on a project that utilizes React with hooks and typescript. My current task involves extracting data from arrays within an array obtained from a JSON response. After handling the data, the structure looks like this: [ [ ...

issue with sending http requests using ionic2/3

I'm still relatively new to using ionic2, even though I have some experience with programming in general. Currently, I'm experimenting with ionic2 and attempting to send simple get/post requests to my locally hosted web services for development p ...

Authorizer custom is not being triggered for websocket connection event

I'm currently working on implementing a custom authorizer for an API Gateway Websocket API. Below is my custom authorizer implementation using CDK: const authFunc = new lambda.Function(scope, utils.prefixed("WebsocketAuth"), { runtime: ...

Issue with hydration in Next.js while trying to access the persisted "token" variable in Zustand and triggering a loading spinner

Below is the code snippet from _app.tsx where components/pages are wrapped in a PageWrapper component that handles displaying a loading spinner. export default function App(props: MyAppProps) { const updateJWT = useJWTStore((state) => state.setJWT); ...

Setting the default value for a useRef<HTMLInputElement> in ReactJs with Typescript

Is there a way to assign a number as the initial value on useRef<HTMLInputElement> without using useState<number>() since the field is a simple counter? Below is my TypeScript code: const MyComponent = () => { const productAmountRef = us ...

Here is a helpful guide on using the replace() function in JavaScript to swap out specific words within a text that match

My task involves manipulating the following text: const a: string = 'I like orange, blue, black, pink, rose, yellow, white, black'; Along with this string: const b: string =['black', 'yellow']; The objective is to replace ...

Angular: Issue with Pipe functionality

Recently, I've encountered an issue with a pipe that I created. Despite having what seems like clear and straightforward code, I can't seem to pinpoint the exact issue. Any thoughts or suggestions on what might be causing this problem? Here&apo ...

Implementing strict validation for Angular @Input by allowing only predefined values

I am facing an issue where I receive a string value as a parameter in a component, but I want to restrict the possible values that can be passed as a parameter, similar to using an enum. Currently, I have: @Input() type: string = ''; However, ...

Converting a string URL to an object type in TypeScript

Is there a way to convert a string URL into an object type in TypeScript? Here is some sample code: type KeyUrl<T> = T extends `/${infer U}` ? U : never; type TUrl<T> = { [k in KeyUrl<T>]: string }; // ---------------------------------- ...

The 'xxx' type is lacking various properties compared to the 'xxx[]' type, such as length, pop, push, concat, and many others

Utilizing typescript and reactjs, the issue lies within this component import type { InputProps } from "../utils/types" const Input = (props: InputProps) => { const makeChildren = () => { return ( <> ...

Error: Uncaught TypeError - The function boss.SetBelongToClan is not defined

Currently, I am faced with an issue while working on a typescript and sequelize project within an express application. The problem arises when trying to create a type-safe interface for utilizing the associate function. Within my Instance interface, there ...

Javascript encounters difficulty in converting timestamp to a date format

I am utilizing this particular function export const getDate = (stamp: string) => { console.log(stamp) //1581638400000 let date : any = Date.parse(stamp) console.log(date) //NaN let month = date.getMonth() let day = date.getDay() ...

What is the best way to invoke a function every 10 seconds in Angular 2?

Is it possible to call a function at specific time intervals in Angular 2? I want the function to be triggered every 10 seconds. For example: num: number = 0; array: number[] = [1,5,2,4,7]; callFuntionAtIntervals(){ if(num==5){ num=0; ...