Creating a Typescript Record without the need to manually define keys

Can someone assist me with Typescript Records?

I'm seeking a solution that eliminates the need for manually typing key names as a key type for a Record, while still maintaining intellisense for that object.

Intellisense example

For instance:

import { StyleProp, TextStyle } from 'react-native';

//I want to avoid typing out numerous keys manually here. 
//Is there a way to automatically retrieve keys already present within the fonts object?
type TFontKeys =
  | 'title'
  | 'subtitle'
  | 'header'
///////

const fonts: Record<TFontKeys, StyleProp<TextStyle>> = {
  title: {
    fontSize: 22,
    fontWeight: '600',
  },
  subtitle: {
    fontSize: 16,
    fontWeight: '600',
  },
  header: {
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 8,
  }}

I am aware I could simply use

Record<string, StyleProp<TextStyle>>

However, this would result in the loss of intellisense for fonts.properties

Without intellisense

If a Record does not serve this purpose, is there an alternative solution available?

Many thanks~

Answer №1

When dealing with object types that cannot refer to themselves, you can easily create a new object using different types. Here's an example:


import { StyleSheet } from 'react-native'

const fonts = {
  title: {
    fontSize: 22,
    fontWeight: '600',
  },
  subtitle: {
    fontSize: 16,
    fontWeight: '600',
  },
  header: {
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 8,
  },
}

export const typedFonts = StyleSheet.create<
  Record<keyof typeof fonts, any>
>(fonts)

Once you have your typedFonts object, you can use it as your style in the project.

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

Best of luck with your project!

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

Custom objects do not return true for Symbol.hasInstance

The TypeScript playground encounters an issue with the Symbol.hasInstance built-in symbol, while it functions properly for other symbols. Testing other symbol methods such as Symbol.match and Symbol.replace show no problems, but Symbol.hasInstance is not ...

Arranging table columns in Angular 2

Having trouble organizing the columns of my table using Angular 2 The transform code for the pipe is as follows: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'orderBy' }) export class OrderByPipe implements Pipe ...

Using an object as an array index in Javascript

I have been utilizing a crossword application from this specific repository: https://github.com/jweisbeck/Crossword . The issue I am facing is that the program is using jquery version 1.6.2 while my entire project is built on jquery-3.1.1 version. The erro ...

Exploring ways to retrieve and manipulate variables from different components in Angular

Currently working on an Angular app using TypeScript: The app.component features a top navigation bar, followed by the router-outlet for other components <navigation></navigation> <router-outlet></router-outlet> Navigation Sectio ...

Substitute the specific class title with the present class

Here is a sample class (supposed to be immutable): class A { normalMethod1(): A{ const instance = this.staticMethod1(); return instance; } static staticMethod1: A(){ return new this(); } } The code above works fine, but how can I re ...

Mastering the Type Checking of React Select's onChange Event Handler

Currently, I am in the process of building a design system based on React TypeScript. For the Dropdown component, I have opted to utilize React Select to handle most of its functionality. To customize the Dropdown component, I have created a wrapper compo ...

What is the best way to utilize Quokka when working with TypeScript files that have been imported?

After installing ts-node using NPM, I've spent countless hours trying to get it to work. Unfortunately, I couldn't find any helpful documentation on the website or through a Google search. I have installed ts-node both globally and in my project ...

What causes the error message "dependency tree resolution failure" related to peers, and how can it be resolved?

I'm encountering an issue while trying to set up React Native Firebase Auth in my React Native application using the following command: npm install --save @react-native-firebase/auth However, I'm running into the following error: ERR! ERESOLVE u ...

What is the best way to display HTML in this particular situation?

This is the function I am working on: public static monthDay(month: number): string { let day = new Date().getDay(); let year = new Date().getFullYear(); return day + ", " + year; } I am trying to add <span></span> tags around ...

Function that returns a lookup map for TypeScript enums

For my React project, I've created a function that transforms a lookup class into an array that can be used. The function is functioning properly, but it seems to loop through the enum twice, resulting in undefined values for the first iteration. Alt ...

Utilizing NestJS to efficiently share an end-to-end server across multiple test suites

Currently, I'm utilizing the NestJS test module to simulate the nest app for testing purposes and my goal is to make this app accessible across various test suites. Here is how I have set it up: test |_ helpers |_ testApp.ts |_ e2e |_ u ...

ESLint Angular now identifies unused variables in type definitions

I've been updating and refining an Angular project (to Angular 8, Electron 6, Ionic 4) and we made the decision to transition from TSLint to ESLint. I've set up some rules and they're working fine, but I'm struggling to get rid of the ...

Using React Material UI in VSCode with TypeScript significantly hampers autocompletion speed

When including the "@mui/material", Visual Studio Code may become unresponsive, leading to Typescript warnings appearing after 10-15 seconds instead of the usual less than 10 milliseconds. For example: import { Button } from '@mui/material&a ...

Understanding Type Syntax: Exploring the Significance of Syntax in Typescript

I'm unfamiliar with Typescript and struggling to grasp the significance of this syntax. Could someone provide some clarification? type Type1<K> = K extends string ? { [P in K]: string } : never; If type K is a subclass of string, does that mea ...

Encountering the issue: "Unable to establish validator property on string 'control'"

Has anyone encountered this error message before? TypeError: Cannot create property 'validator' on string 'control'" import { Component, ChangeDetectionStrategy, OnInit } from '@angular/core'; import { CommonModule } from &ap ...

Using Typescript to declare types for an object that is capable of generating an outcome

If I have an object structured like this let obj = { property1:()=>{ return Date()} // for example, it doesn't have to be a date property2:()=>{ return 1} } Now, I want to convert this to the following type structure { property1: ...

An interface that is extended by an optional generic parameter

I currently have an exported abstract class that has one generic. However, I now require two generics. I do not want to modify all existing classes that are using this class. Therefore, I am looking to add an optional generic class that extends an interfac ...

Angular2 data binding does not update when properties change

I'm struggling to establish the connection between the fields and the component in order for them to update when the properties change in OnDataUpdate(). The field "OtherValue" successfully binds two ways with the input field, and the "Name" field di ...

How can the Singleton pattern be properly implemented in Typescript/ES6?

class Foo{ } var instance: Foo; export function getFooInstance(){ /* logic */ } or export class Foo{ private static _instance; private constructor(){}; public getInstance(){/* logic */} } // Use it like this Foo.getInstance() I would ...

At what point do we employ providers within Angular 2?

In the Angular 2 documentation, they provide examples that also use HTTP for communication. import { HTTP_PROVIDERS } from '@angular/http'; import { HeroService } from './hero.service'; @Component({ selector: 'my-toh&ap ...