Transforming Typescript types into object literals

type SelectData = {
  name?: boolean;
  address?: boolean;
}

const selectData: SelectData = {
  name: true
}

const untypedSelectData = {
  name: true
}

I am looking to enforce TypeScript to throw an error if there is an attempt to assign a property that does not exist in the SelectData type:

const selectData: SelectData = {
  age: true
}

How can I ensure that the type of selectData remains consistent with untypedSelectData ({name: boolean})?

Answer №1

To ensure that an object is compatible with a weaker type at compile time while preserving a stronger inferred type for the variable or constant it's assigned to, you can employ a generic identity function.

function validateData<T extends SelectData>(data: T): T {
  return data;
}

// type is { name: true }
const selectData = validateData({
  name: true
})

// error: object literal may only specify known properties
const errorData = validateData({
  age: 23
})

Playground Link

As @jcalz points out, there is a feature request on the official GitHub tracker for achieving this functionality without the need for additional function declarations and calls, but as of now, such a feature has not been implemented.

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

Dynamically change or reassign object types in TypeScript

Check out the example you can copy and test in TypeScript Playground: class GreetMessage { message: {}; constructor(msg: string) { let newTyping: { textMsg: string }; // reassign necessary this.message = newTyping; this.message.textMsg = msg; ...

Angular's ng-model is unable to access the value of an object array

When selecting the days, users should be able to input check-in and check-out time ranges dynamically. However, there seems to be an issue with retrieving the values and data format. The ng model is unable to capture the check-in and check-out values. The ...

Can the detectChanges() method in Angular cause any issues when used with the form control's valueChanges event?

Within my parent Component, I am working with a formGroup and updating its value using patchValue method. ngAfterViewInit() { this.sampleform.controls['a'].patchValue ...} I then pass this form to a child component in the parent component's ...

Transferring information to a navigated module using Angular2

I am currently facing a scenario where I have a component being loaded via routing, and my goal is to pass data from the parent component into this child component. How exactly can I achieve this task effectively? Parent Component Class export class Home ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...

Looking to develop a dynamic password verification form control?

I am in the process of developing a material password confirmation component that can be seamlessly integrated with Angular Reactive Forms. This will allow the same component to be utilized in both Registration and Password Reset forms. If you would like ...

How can I display every index from my JSON Fetched Files?

In the picture shown here, I have a series of Tables being displayed: https://i.sstatic.net/YUZD1.png The issue highlighted in red is that I want to show the Index of each JSON array as the Table number. Below is the code snippet: function getExternal( ...

Incorporate a JavaScript library into a personalized JavaScript file that is utilized within my Angular2 project

Integrating Machine Learning into my Angular2 project using the "synaptic.js" JavaScript library is my goal. After executing the command npm install synaptic --save I intend to execute a custom javascript file (myJsFile.js): function myFunction() { v ...

What could be causing React to generate an error when attempting to utilize my custom hook to retrieve data from Firebase using context?

Currently, I am restructuring my code to improve organization by moving data fetching to custom hooks instead of within the component file. However, I am encountering issues with the hook not functioning properly when used in conjunction with my context. ...

Using HTTP POST to subscribe and implementing a try-catch block

When using Angular2's http.post, I encountered an issue where the headers were not sent to the CORS server. To address this, I attempted to create a loop that would retry the request until it succeeds. However, this resulted in an endless loop. How ca ...

Leverage context to facilitate communication between components operating at various levels of the system

I am currently working on the settings pages of my applications. Each page features a common SettingsLayout (parent component) that is displayed across all settings pages. One unique aspect of this layout is the presence of an ActionsBar, where the submit/ ...

Issues with CSS Styling not being applied properly on mobile devices in a React App deployed on Heroku

The Dilemma My React app is deployed on Heroku using create-react-app for bundling. The backend is a Node.js written in Typescript with node version 10.15.3. Locally, when I run the site using npm start, everything works perfectly. However, when I view t ...

Is there a way to prompt TypeScript to report an error when a mapped key is missing?

Here is my current code snippet: type TransferType = 'INTERNAL' | 'WITHDRAWAL' | 'DEPOSIT' type TransferEvents = Record<TransferType, Record<string, TypeFoo | TypeBar>> export interface EventsTooltip extends Tran ...

Issue with Angular ngFor: displaying only one name instead of all names in the loop

In my component.ts file, I have retrieved this data from an API call: [ [ { "name": "name one", "desc": "something here", }, { "name": &quo ...

Is seamless integration possible between Angular2 and jQuery plugins?

When attempting to integrate jQuery plugins with Angular 2, there are three distinct scenarios: 1. ONLOAD: Initializing the plugin on page load works smoothly with the following code snippet: ngAfterViewChecked(){ ... $('#somedatatable1&apos ...

What is the method for choosing an element by class name in TypeScript?

Currently, I'm working on creating a responsive menu bar that collapses on smaller screens. The challenge I'm facing is that I'm using TypeScript for this project. Is there any guidance on how to translate the following code into TypeScript? ...

Using ngModel to bind data within an Angular dialog box

I'm facing an issue with my project where changes made in the edit dialog are immediately reflected in the UI, even before saving. This causes a problem as any changes made and then canceled are still saved. I want the changes to take effect only afte ...

Transporting a Typescript file to the customer using JavaScript

As a newcomer to typescript and in the process of creating a small application in visual studio 2013, I have noticed that when viewing the project in Chrome's developer tools, typescript files (*.ts) are being downloaded to the client. This could pote ...

Is there a way to modify the button exclusively within the div where it was pressed?

I plan to incorporate three buttons in my project (Download, Edit, and Upload). Upon clicking the Download button, a function is triggered, changing the button to Edit. Clicking the Edit button will then change it to Upload, and finally, clicking the Uplo ...

Utilizing Angular2 with Webpack in Visual Studio 2015

Is there a way to utilize Visual Studio 2015 alongside Webpack and Angular2? I have successfully created an Angular2 App with VS, but now that I've added Webpack to build my app, I would like to debug all of my code using IIS Express. I want to be abl ...