How can you determine the data types of properties within a blank class object using Typescript and Angular?

Class Example{
  constructor(
     public x: number,
     public y: string
   ) {}
}
let e = new Example();

Is there a way to programmatically determine the data type of e.x or e.y in TypeScript?

Answer №1

TypeScript is great at catching errors at compile time, but when dealing with external data, it falls short. This is where runtime type checking comes in handy - enter io-ts.

Here's an example using io-ts:

const Person = t.type({
  name: t.string,
  age: t.number
})

// Perform a runtime check
const result = Person.decode({ name: 'Giulio' })

console.log(PathReporter.report(result))
// => ['Invalid value undefined supplied to : { name: string, age: number }/age: number']

ThrowReporter.report(result)
// => throws 'Invalid value undefined supplied to : { name: string, age: number }/age: number'

interface IPerson extends t.TypeOf<typeof Person> {}

function getName(person: IPerson): string{
  return person.name;
}

// Check at compile time
getName({ name: 'Giulio' });

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

What is the process for attaching a key signature onto a string in order for it to function as an index for an object?

How can I specify a signature in TypeScript to indicate that the current value might be used as an index for accessing a specific object? I am encountering the error: Element implicitly has an 'any' type because expression of type 'string&ap ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. https://i.sstatic.net/Ouot4.png https://i.sstatic.net/MMKjm.png H ...

Guide on accessing an element from a predicate object in Typescript while using Angular

I'm trying to wrap my head around how to access an element that exists on an object of a specific type but is defined as a type predicate. For example, let's say we have a Team defined as: let team$: Observable<ErrorModel | Team> The res ...

Is there a way to utilize an Event Emitter to invoke a function that produces a result, and pause until the answer is provided before continuing?

Looking for a way to emit an event from a child component that triggers a function in the parent component, but with a need to wait for a response before continuing. Child @Output() callParentFunction = new EventEmitter<any>(); ... this.callParen ...

This error message in AngularJS indicates that the argument 'fn' is not being recognized as a function

I am currently working with angularjs and typescript and I am attempting to create a directive in the following manner: Below is my controller : export const test1 = { template: require('./app.html'), controller($scope, $http) { ...

Issue with decompressing the identical data using zlib (Z_BUF_ERROR)

Below is the Python code snippet I am working with: import zlib raw = bytes.fromhex("789C34C9410AC2301005D0BBFC752289A88BB94A53CAD8061B48D3329D2A1A7277DDB87BF02A14548E9C0DF63FD60DE49DC104AA98238BDE23EB908A467972065DFCF9FAFB4185C708EAD0053C58E38BDF769 ...

Utilizing Angular 2 for transforming JSON data into Angular classes

I have been working through the Angular2 getting started guide to kickstart my own application development. So far, I have managed to retrieve JSON objects from a local file and display them in angular2 templates. However, the challenge arises when the str ...

Determine the amount of time that can be allocated based on the attributes contained within the object

I am faced with a JSON structure like the one below: var meetings = [ { id: '1', start_time: "2020-11-15T08:30:00+00:00", end_time: "2020-11-15T14:15:00+00:00" }, { id: '2', start_time: &quo ...

Modify information in formArray

Let's take a look at this setup I have: Model: export class MapDetailModel{ id: number; lat: number; lon: number; alt: number; long: number; angle: number; distance?: number; pendenza?: number; } Html: <div clas ...

Steer clear from using the implicit 'any' type while utilizing Object.keys in Typescript

I have a unique situation where I need to loop over an Object while maintaining their type without encountering the error "Element implicitly has an 'any' type because 'ContactList' has no index signature". Despite extensive discussion ...

The function 'transformArticles' is not recognized as a property of the object 'Article'

I'm encountering an issue with Typescript that I need help understanding. In my code, I have a route where I am importing a class called Article like this: import { Request, Response } from "express"; const appRoot = require("app-root-path"); import ...

Error encountered with object.map() function - what fundamental concept am I missing?

Could someone lend me a fresh set of eyes on this... The React Component is fetching data from MariaDB using a useEffect() hook. The data is retrieved successfully without any errors, and the console.log shows the correct data (refer to the image below). ...

What are the steps to configure JSS in a TypeScript/NextJS application?

Trying to set up a basic web app using React, TypeScript, NextJS, and Material-UI has been quite the challenge. The main issue I am facing revolves around styling within my project. To better illustrate my problem, I have created a CodeSandbox environment. ...

Leveraging Google Analytics with Angular 4 and beyond

Having trouble integrating Google Analytics with Angular 4? Can't seem to find the @type for ga.js in ts? Here's a quick fix that I implemented in every component: declare let ga: any; How did I solve it, you ask? I created a function to dyna ...

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Ways of modifying the readonly and required attributes of an HTML element using Angular2 Typescript

I am facing an issue with changing input field attributes back and forth in some of my components. I have a code that successfully changes the readonly attribute as needed. However, when trying to change the required attribute, Angular2 still considers the ...

Leveraging external Javascript files in Ionic framework version 3 and above

Hey there, I'm currently working on integrating the Mapwize SDK, an external Javascript library, with the latest version of Ionic. I've encountered the common challenge of getting Javascript to function smoothly with Typescript. Although I'm ...

Shifting successive elements in an array alternates

I have been working on a pick list component and have come up with the following layout https://i.stack.imgur.com/TnHAp.gif Whenever I try to move consecutive items, it keeps toggling between those two Here's a snippet of my code: moveDown(){ ...

Turning an array of strings into a multidimensional array

I have a JavaScript string array that I need to convert into a multidimensional array: const names = [ "local://john/doe/blog", "local://jane/smith/portfolio", "as://alexander/wong/resume" ]; The desired output sh ...