Create typings for object properties in TypeScript

I am inexperienced with TypeScript and am looking to set up types for my object keys. I have explored a few methods to accomplish this, but I am encountering an issue where an error is not triggered when assigning a value of a different type. For example:

interface sectionProp { 
    _type1: String,
    _columnStrechAllowed: Boolean,
    _columnOccupancy: Number,
    is_mandatory: Boolean
}


export class sectionProperties {
  folioSectionContentProp = <sectionProp> {}

  constructor(type?) {
    this.folioSectionContentProp._type1 = type;
    this.folioSectionContentProp._columnStrechAllowed = false;
    this.folioSectionContentProp._columnOccupancy = 6;
    this.folioSectionContentProp.is_mandatory = false;
  }

}

export class createNewSection extends sectionProperties {
  constructor() {
    super("Test") // here I will assign value
 // super(12)     //@ this does not generate any error as well
 // I might assign value by some other way (from object creation) 
 // but I want to know the reason if type is defined then it should 
 // not accept any value other than type 
  }

}

var z = new createNewSection();
console.log(z)

In conclusion, I am striving to ensure that my object keys are explicitly typed.

Many thanks

Answer №1

The issue lies in the fact that you have not explicitly defined a value for the type parameter in the constructor of sectionProperties, leading it to default to any. This means that any type of value can be assigned to and from it. To rectify this, you need to provide a specific type annotation:

interface sectionProp {
    _type1: String,
    _columnStrechAllowed: Boolean,
    _columnOccupancy: Number,
    is_mandatory: Boolean
}


export class sectionProperties {
    folioSectionContentProp = <sectionProp>{}

    constructor(type: string) {
        this.folioSectionContentProp._type1 = type;
        this.folioSectionContentProp._columnStrechAllowed = false;
        this.folioSectionContentProp._columnOccupancy = 6;
        this.folioSectionContentProp.is_mandatory = false;
    }

}

export class createNewSection extends sectionProperties {
    constructor() {
        super("Test") // assigning a value here
        // super(12)     //this would result in an error
    }

}

To avoid such issues, it is recommended to enable the noImplicitAny compiler option to enforce explicit type declarations where inference is not possible.

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

Is there a way for one function to access the validation of a nullable field performed by another function?

Below is a TypeScript code snippet. The function isDataAvailable will return true if the variable data is not undefined. However, an error occurs in the updateData function when trying to access data.i++: 'data' is possibly 'undefined'. ...

What is the process for deploying a Lambda function using Terraform that has been generated with CDKTF

Currently, I am following a tutorial by hashicorp found at this link. The guide suggests using s3 for lambda deployment packages. // in the process of creating Lambda executable const asset = new TerraformAsset(this, "lambda-asset", { ...

Ionic 3: Struggling to Access Promise Value Outside Function

I've encountered an issue where I am unable to retrieve the value of a promise outside of my function. It keeps returning undefined. Here's what I have attempted so far: Home.ts class Home{ dd:any; constructor(public dbHelpr:DbHelperProvider ...

How can you limit a type reference to a specific file in TypeScript?

Currently, I am working on writing universal JavaScript code that can be used in both Node and browser environments. While most of the code works independent of the environment, there are certain parts where different implementations are required based on ...

Having trouble mocking Node fs Modules using Sinon

I am facing an issue with mocking the promises methods of the node fs module in my code. When my appData.ts file is executed, it calls the actual fs.promises.mkdir method instead of the mock function defined in \__tests__/appData.test.js. I suspect ...

Arranging Typescript strings in sequential date format

Looking for guidance on how to sort string dates in chronological order, any expert tips? Let's say we have an array object like: data = [ {id: "1", date: "18.08.2018"} {id: "2", date: "05.01.2014"} {id: "3", date: "01.01.2014"} {id: ...

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...

Can a VS Code theme extension be designed using JavaScript or TypeScript rather than JSON?

Currently working on a VS Code theme extension, I am interested in exploring the possibility of using JavaScript or TypeScript files instead of a JSON file. The idea of having all the theme information crammed into one massive JSON file feels disorganize ...

Maintaining checkbox selection while switching pages in Angular

When I try to edit the settings for accepting payments in all currencies under the "Pricing" component, the checkbox is unchecked every time I return to the "General" section. How can I prevent this from happening and keep the checkbox checked? Refer to ...

Is there a way to utilize "npm install ts-node-dev -D" in Termux?

npm ERR! code EACCES npm ERR! syscall symlink npm ERR! path ../acorn/bin/acorn npm ERR! dest /storage/emulated/0/bot-baiano/node_modules/.bin/acorn npm ERR! errno -13 npm ERR! Error: EACCES: permission denied, unable to create symlink fro ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

What is the equivalent of getElementById in .ts when working with tags in .js?

Looking to incorporate Electron, Preload, Renderer with ReactJS and TypeScript into my project. <index.html> <body> <div id="root" /> <script src='./renderer.js'/> </body> <index.ts> const root = Re ...

What is the syntax for using typeof with anonymous types in TypeScript?

After reading an article, I'm still trying to grasp the concept of using typeof in TypeScript for real-world applications. I understand it's related to anonymous types, but could someone provide a practical example of how it can be used? Appreci ...

Is it possible to maintain component data in Angular while also incorporating dynamic components?

All the code you need can be found here: https://stackblitz.com/edit/angular-keep-alive-component?file=src/app/app.component.ts Is it possible to maintain the state of entered values when switching components? I am currently utilizing dynamic component r ...

Ways to modify the input field value in my form based on the current page context

I am currently developing a website for a sports event organization company using Angular, HTML/CSS. The focus of this website is on the triathlon sport and it consists of several stages. On the home page, there are five image tags representing each stage ...

TypeScript utility function that retrieves properties from an interface based on a specified type

Is there a way to create a new object type that includes only properties from another Object that match specific types, as opposed to property names? For example: interface A { a: string; b: number; c: string[]; d: { [key: string]: never }; } int ...

Angular 9 Issue: Failure to Display Nested Mat-Tree Children

Hello everyone, I'm new to posting questions on Stack Overflow and I'm seeking some assistance with an issue I'm having with Mat-Tree. Despite the fact that my data is present when I console log it, the children are not appearing. I am fetc ...

Mastering the art of throwing and managing custom errors from the server to the client side within Next.js

I'm in the process of developing a Next.js application and I am faced with the challenge of transmitting customized error messages from the server to the client side while utilizing Next JS new server-side actions. Although my server-side code is func ...

Steps for linking HTTP requests in Angular 2 depending on the type of response

My attempt to create an api call from a remote server and then, if an error occurs, make another request from my local server is not working as expected. I am encountering errors and need help to determine if my approach is feasible. Here is the code snip ...

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 }>( ...