Is it possible to assign an object literal to a typed variable in TypeScript? Can you also specify the typeof object literal?

Consider a scenario where you have the following type definition:

type MyType = {
   A: number | string
}

If you try to assign a value like this, TypeScript will correctly flag it as an error:

const myValue1: MyType = {
   A: 123,
   B: "Oh!", // This will raise a type error since property B was mistakenly defined
}

Alternatively, if you define a variable without explicitly specifying its type, you can extract the type of the object literal in this way:

const myValue2 = {
   A: 123
}
const MyLiteralType = typeof myValue2; // Result: {A: number}

Ideally, you might want both scenarios:

  • To enforce strict checking when assigning values to variables (disallowing additional properties), and
  • To automatically extract the type of the object literal.

Is there a clever way to achieve this in TypeScript without having to redundantly define a second type ({A: number})? Any suggestions are welcome!

It appears that TypeScript currently only supports one of these features at a time:

  • You can either get strict type checking by assigning an object literal to a typed variable, or
  • You can extract the type of the object literal but sacrifice strict type enforcement.

Perhaps there's a workaround using template tricks to compare the types (MyType and MyLiteralType) and throw an error if extra properties are detected?

Answer №1

This specific scenario perfectly showcases the utility of the satisfies operator:

type MyType = {
   A: number | string
};
const myValue2 = {
   A: 123
} satisfies MyType;
const myValue1 = {
   A: 123,
   B: "Oh!", // triggers a type error due to an unintentionally defined property B
} satisfies MyType;
type MyLiteralType = typeof myValue2; // {A: number}

(View online demonstration)

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 TypeScript's Conditional Types

Consider this scenario: type TypeMapping = { Boolean: boolean, String: string, Number: number, ArrayOfString: Array<string>, ArrayOfBoolean: Array<boolean> } export interface ElemType { foo: keyof TypeMapping, default: valueof T ...

I need help with querying the date format in Mongoose and MongoDB. The specific date I am trying to query is stored in the field "ticketTimeStartDate" and is in the format: "Mon Oct 18 2021 12:28:59 GMT+0000 (

Can anyone provide guidance on querying this specific date format in moongose and MongoDB? The date field is as follows: "ticketTimeStartDate": "Mon Oct 18 2021 12:28:59 GMT+0000 (Coordinated Universal Time)", ...

Conditioning types for uninitialized objects

Is there a way to create a conditional type that can determine if an object is empty? For instance: function test<T>(a: T): T extends {} ? string : never { return null } let o1: {} let o2: { fox? } let o3: { fox } test(o1) ...

Looking to personalize the MUI - datatable's toolbar and place the pagination at the top?

I successfully managed to hide the toolbar icon, but I am struggling with positioning pagination from bottom to top. Additionally, I am attempting to add two buttons (reset and apply) in the view-Column toolbar without any success in customizing the class. ...

What is the C sharp version of this code structure?

I'm curious to know what the C# syntax is for declaring a property like this: filters: { [arg: string]: string }; ...

What is the method for defining a function within a TypeScript namespace?

Suppose there is a namespace specified in the file global.d.ts containing a function like this: declare namespace MY_NAMESPACE { function doSomething(): void } What would be the appropriate way to define and describe this function? ...

What is the correct way to declare a variable with a generic type parameter?

Exploring the following code snippet that showcases a React component being defined with a type argument named TRow: function DataTable<TRow> ({ rows: TRow[] }) { return ( ) } Prior to this implementation, ES6 was utilized and components were c ...

Extract from Document File

After receiving a PDF through an Angular Http request from an external API with Content Type: application/pdf, I need to convert it into a Blob object. However, the conventional methods like let blobFile = new Blob(result) or let blobFile = new Blob([resul ...

"Exploring the process of creating a custom type by incorporating changes to an existing interface

One of the challenges I'm facing is defining an object based on a specific interface structure. The interface I have looks like this: interface Store { ReducerFoo : ReducerFooState; ReducerBar : ReducerBarState; ReducerTest : ReducerTestSt ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Extending Interfaces Using Keys from an Array in Typescript

When dealing with a scenario where you want a pointfree omit, you can achieve this: type PlainObject<T> = {[key: string]: T} const omit = <K extends string>( name: K ) => <T, U extends PlainObject<T> & { [P in K]: T }>( ...

Displaying error messages in Angular Material upon clicking a button

I am struggling with validation using the <mat-form-field> and <mat-error>. The validation works as expected when the user tabs out of the input without filling it. However, I'm facing a challenge in making this error show up when a button ...

Determine the presence or absence of data in an Angular Observable

Here is an example of how I am making an API call: public getAllLocations(): Observable<any> { location = https://v/locations.pipe(timeout(180000)); return location; } In my appl ...

How to toggle visibility of child elements in an HTML template using Angular 4+

I'm currently working on incorporating a basic "hover over a comment to display a reply button" feature in my angular application. Is it possible to create this effect using template reference variables exclusively? Something like this... <mat-l ...

How can I exclude *.d.ts files from tslint checking?

Recently, I decided to integrate tslint into my workflow. Following the installation steps, I used the command: npm install tslint tslint-config-ms-recommended --save-dev My configuration file tslint.json now looks like this: { "extends": "tslint-co ...

How can I conceal an element upon page load using Ionic framework?

index.component.ts initialize() { // Execute necessary functions after loading this.index.ready().then(() => { if(this.index.is('core')){ // this.menu.enable(false, 'mobileOnlyPages'); }else{ ...

Guide to integrating global interfaces into your Nuxt project

Recently diving into the world of Nuxt 3, I've encountered a challenge while exploring TypeScript functionalities. My current goal is to create a versatile NavBar featuring multiple buttons with unique links. To achieve this, I aimed to establish an ...

How can I transfer data to a different component in Angular 11 that is not directly related?

Within the home component, there is a line that reads ...<app-root [message]="hii"> which opens the app-root component. The app-root component has an @input and {{message}} in the HTML is functioning properly. However, instead of opening t ...

Enhance Typescript with Extension Traits

Picture this scenario: You have a class A with a method that can create an instance of class B. You're unable to make any changes to the code of either A or B, as they are part of an external library. In this situation, if you want to enhance the fun ...

Tips for utilizing ngIf based on the value of a variable

Here is the code from my file.html: <button ion-button item-right> <ion-icon name="md-add-circle" (click)="save();"></ion-icon> </button> The content of file.ts is: editmode = false; I am trying to achieve the foll ...