Explain the form of an object using typescript without considering the categories

I'm looking to define the shape of an object in TypeScript, but I want to disregard the specific types of its fields.

interface TestInterface {
  TestOne?: string;
  TestTwo?: number;
  TestThree?: boolean;
}

My approach was to define it like this:

type Shape = { [fieldName: string]: any };

type ShapeType<TShape extends Shape> = TShape;

var test: ShapeType<TestInterface> = {
  TestThree: "asdf",
}

This should raise a concern if done as follows:

var test: ShapeType<TestInterface> = {
    TestThree: "asdf",
    TestFour: "123",
}

If I cast "asdf" to any, it works. Is there another way to define this without needing casting?

Edit: The intention is to have a shape mainly used for data exchange, but occasionally utilized for metadata. In such instances, only the structure matters, not the type (at least for now - eventually, the plan is to convert the shape's types to another specified type).

Answer №1

In terms of declaration, I fail to see the benefit of labeling something as boolean only to later assign it as a string...

However, we can make adjustments as follows:

//type ShapeType<TShape extends Shape> = TShape;
interface Shape { [fieldName: string]: any };

// now, TestInterface also contains [fieldName: string]
interface TestInterface extends Shape {
  TestOne?: string;
  TestTwo?: number;
  TestThree?: boolean;
}


type ShapeType<TShape extends Shape> = TShape;

// BTW - why we declared TestsThree to be boolean
// if we assign it to string... that would hardly help
var test: ShapeType<TestInterface> = {
    TestsThree: "asdf",
}

Alternatively, if we prefer not to use Shape as an interface,

// we have to do this explicitly [fieldName: string]
interface TestInterface {
  [fieldName: string]: any 
  TestOne?: string;
  TestTwo?: number;
  TestThree?: boolean;
}

type Shape = { [fieldName: string]: any };

type ShapeType<TShape extends Shape> = TShape;

var test: ShapeType<TestInterface> = {
    TestsThree: "asdf",
}

Both methods are functional, but once more, the rationale behind defining TestThree?: boolean; and then assigning it as TestsThree: "asdf", eludes me.

Answer №2

It seems like this code snippet was created a while back, but I recently encountered a similar issue. It appears that you are looking to define a type for an object with the same properties, but typed as 'any' instead of their original types.

type ShapeType<T> = { [key in keyof T]?: any };

// This is valid
const test1: ShapeType<TestInterface> = {
    TestsThree: "asdf",
}

// You will get an error saying "TestFour" is not a valid property
const test2: ShapeType<TestInterface> = {
    TestThree: "asdf",
    TestFour: "123",
}

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

The compatibility of return value types between the constructor signature and the call signature interface is not maintained when they are used together

I'm new to TypeScript and I'm struggling to figure out why I'm getting a type error in the code below. Can someone help me identify what's wrong? interface CallOrConstruct { new (value: string): Person (value: number): number } cla ...

What is the significance of utilizing an empty value `[]` for a typed array interface instead of using an empty `{}` for a typed object interface?

Why can I initialize friends below as an empty array [], but not do the same for session with an empty object {}? Is there a way to use the empty object without needing to make all keys optional in the interface? const initialState: { friends: Array< ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

How do React Native proxies differ from vanilla React proxies in their functionality?

Trying to retrieve data from an API running locally on port 5000 of my device, I recalled setting the proxy in package.json when working on React web applications: "proxy": "https://localhost:5000" Attempting to fetch information f ...

Is it necessary to wait for the resolve function when using hooks in SvelteKit?

i have implemented this handle function for SvelteKit hooks and since it returns a promise of response, the resolve function does not necessarily need to be awaited. This is because it is a function that either directly returns a value or returns a promise ...

Automatic Formatting of Typescript in SublimeText

Utilizing Microsoft's Typescript Sublime Plugin, I am able to format a file using the shortcut ^T ^F as outlined in the plugin's feature list. Is there a method to automatically execute this command when saving a file? Similar to the functionali ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

Using Generators with the for...of loop in Typescript

I am currently facing an issue with Typescript when trying to compile a generator-loop that works perfectly in a modern browser. The code snippet in question is: /** Should print "x= 1 y= 2" **/ function* gen() { yield [1, 2] } for (const [x, y] of gen()) ...

Tips on displaying hyperlinks within a text area in an Angular application

In my Angular application, I am facing an issue with displaying hyperlinks within a text area box for dynamic content. The hyperlinks are not recognized and therefore cannot be clicked. Can someone please advise on how to properly display hyperlinks with ...

Is there a method to initiate a 'simple' action when dispatching an action in ngrx?

Here's the scenario I'm facing: When any of the actions listed below are dispatched, I need to update the saving property in the reducer to true. However, currently, I am not handling these actions in the reducer; instead, I handle them in my ef ...

Managing a scenario with a union type where the value can be retrieved from one of two different functions

There are two similar methods that I want to refactor to eliminate redundant code. The first function returns a single element, while the second function returns multiple elements: //returns a single element const getByDataTest = ( container: HTMLElement ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

The object's type remains a mystery

While working on implementing jwt authentication in Ionic, React with TypeScript, I faced a typescript error when trying to add a check in my App.tsx file after successful implementation. The error stated: Object is of type 'unknown' Below is ...

Understanding the concept of a "class variable" in Typescript when referring to a variable that belongs to another class

When we declare a variable at the class level and assign it the type of another class, such as in the following code: let greeter: Greeter; //line 1 greeter = new Greeter("world"); What is contained within 'greeter' on line 1? ...

Is TypeScript inadvertently including unnecessary files in its compilation?

In my configuration file, tsconfig looks like this: { "compilerOptions": { "module": "esnext", "target": "es6", "declaration": true, "outDir": "./dist", }, "include": [ "src/**/*" ] } Let's consider a simple source file f ...

Functions outside of the render method cannot access the props or state using this.props or this.state

Just starting out with react. I've encountered an issue where a prop used in a function outside the render is coming up as undefined, and trying to use it to set a state value isn't working either. I've researched this problem and found va ...

Combining React Context and Typescript using a Custom Hook

I have been working on a context provider in React and Chakra-UI, but I seem to be facing some issues: import { useBoolean } from "@chakra-ui/react" import { createContext } from "react" const MobileContext = createContext<typeof us ...

Input values that are true, or in other words, fulfill conditions for truthiness

Is there a specific data type in TypeScript to represent truthy values? Here's the method I'm working with: Object.keys(lck.lockholders).length; enqueue(k: any, obj?: any): void It seems like TypeScript allows checking for empty strings &ap ...

Contrasting Compositions with Generics

Let's consider a scenario where we have an abstract class A and three concrete classes that inherit from it: A1, A2, and A3. There is also another hierarchy tree with an abstract class B and three concrete classes B1, B2, and B3. Each concrete class A ...

Exploring the integration of the mongodb-stitch library within an Angular 4 application

I have been experimenting with the MongoDB Stitch service in Angular, and so far I have successfully implemented the service. However, the only way I have managed to connect to the service is by adding the js library hosted on AWS directly into the html pa ...