Is there a way to verify whether a key within an Interface corresponds to a class that is a subclass of a specific Parent

Is there a method in typescript to ensure that a property in an interface must be of type "child subclass C, which extends class P"?

example.ts

import { P } from '/path/to/types'
class C extends P {
   ...
}

types.ts

// `C` cannot be accessed here
class P {
   ...
}


interface {
    myProp: ???? <-- how to ensure `myProp` is a subclass of P (class, not instance)?
}

Alternatively, I could verify

Object.getPrototypeOf(myProp.prototype) === P.prototype
at runtime. Is there a way to enforce this requirement through types at compile/checker time?

Answer №1

To determine the type, you can utilize the typeof method:

class P { ... }
interface Foo {
    myProp: typeof P
}
//Implementation
class C extends P { ... }
class D { ... }
//Valid
var f: Foo = {
    myProp: C
}
// Invalid
var f2: Foo = {
    myProp: D
}

This approach ensures that the chosen class for the property aligns with P.

Update

Considering that Typescript follows structural compatibility, any class matching the structure of P will be deemed compatible with typeof P. However, if P consists solely of public members and a limited number of members, there is a possibility that another class could unintentionally have a similar structure. To exclusively allow classes directly inheriting P to be compatible, a private member can be incorporated into P to render it incompatible with other classes (variations in private field declarations do not equate to compatibility).

class P { private nonStructural:true }
interface Foo {
    myProp: typeof P
}
//Implementation
class C extends P { }
class D { private nonStructural:true }
//Valid
var f: Foo = {
    myProp: C
}
// Invalid
var f2: Foo = {
    myProp: D
}

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

Quick way to specify type for Observable in Typescript

Exploring Shortcut Declarations When working with TypeScript, I often take a shortcut when declaring object shapes. Instead of creating an interface first and then specifying that the object conforms to that type, I simply do: object: { fizz: boolean, buz ...

Getting the local path of a file from an input file in Angular 7

Is there a way to retrieve the local file path from an input field in HTML? After running the code below, I obtained 'C:\fakepath\fileTest.txt' I am looking for a method to get the local path so that I can pass it on to my control ...

Having trouble with the react event handler for the renderedValue component in Material UI?

I am facing an issue while trying to utilize the onDelete event handler within the chip component using Material UI in the code snippet below. Upon clicking on the chip, it triggers the Select behavior which opens a dropdown menu. Is there a way to modif ...

Leverage Async Await for Setting Response Data in TypeScript

Currently, I am making multiple API requests with different data and storing all the responses in an array. Then, I am using .map to map the response array to my original array to update the data. However, it seems like the process is not working correctly ...

Is there a way to retrieve the initial item of a JSON array from an HTML document using Angular 2?

Within the src/assets/ directory, I have a json file called product.json with the following structure: [ { "images": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png", "textBox": "empty", "comments": "empty" }, { "i ...

Utilize Angular 2 Form Elements Again

I'm currently in the process of working on a project with Angular and I want to make sure that my form components can be used for creating and updating entities seamlessly. Let's say I have a User entity stored on a remote API, and I have a form ...

Restricting HTTP requests to once every 200 milliseconds in Angular 4 with filtering in place

In my current project, I am working on a page that utilizes an ngFor to display an array of objects. One of the features I want to implement is the ability for users to filter these objects by entering specific keywords in an input field. Since the data f ...

A guide on utilizing the useEffect hook to dynamically update a button icon when hovering over it in a React application

Is it possible to change the icon on a button when hovering using useEffect? <Button style={{ backgroundColor: "transparent" }} type="primary" icon={<img src={plusCart} />} onCl ...

Creating a read-only DIV using Angular - a step-by-step guide

Is there a simple way to make all clickable elements inside a div read only? For example, in the provided HTML code, these divs act like buttons and I want to disable them from being clicked. Any tips or shortcuts to achieve this? Thank you. #html < ...

Unexpected token { in Fuse-Box when using Typescript

Here's the beginning of my fuse.ts file import { CSSPluginOptions } from 'fuse-box/plugins/stylesheet/CSSplugin'; import { argv } from 'yargs'; import * as path from 'path'; import { CSSPlugin, CSSResourcePlugin, Env ...

Tips for verifying the presence of a specific value within an array of union types

Given an array of a specific union type, I am trying to determine if a string from a larger set that includes the union type is present in the array during runtime: const validOptions: ("foo" | "bar")[] = ["foo", "bar"] type IArrType = typeof validOptions ...

Developing a constructor method that is conscious of data types

In my current scenario, I am dealing with a set of types: X, Y, and Z, all of which extend the same common interface J. My goal is to define a method that looks like this: class MyClass { private someNumber = 1; private someProperty; addEleme ...

What is the unit testing framework for TypeScript/JavaScript that closely resembles the API of JUnit?

I am in the process of transferring a large number of JUnit tests to test TypeScript code on Node.js. While I understand that annotations are still an experimental feature in TypeScript/JavaScript, my goal is to utilize the familiar @Before, @Test, and @Af ...

What is the best way to export an overloaded function in TypeScript?

Trying to figure out how to overload a function in TypeScript so it can determine the type of arg2 based on the value of arg1. Arg1 has a list of known values. Here's a rough example of what I'm attempting: interface CatArgs {legs : number} int ...

Tips for assessing the prop that is being passed to a styled component with React and TypeScript

I am trying to apply a background color to a styled component div only if the state "active" is true. This is how I am currently attempting to do it: function Main() { const [active, setActive] = useState(false); return ( <ChildCompone ...

Enhancing ES6 capabilities with Angular polyfills

While exploring the Angular documentation and various online resources about Angular, I came across a question. If all code is written in Typescript, why would we need ES6 polyfills? My understanding is that webpack eventually transpiles the code to ES5, s ...

Animating Angular ng-template on open/close state status

I am looking to add animation when the status of my ng-template changes, but I am unable to find any information about this component... This is the code in my report.component.html <ngb-accordion (click)="arrowRotation(i)" (panelChange)="isOpen($even ...

Implementing Generic Redux Actions in Typescript with Iterable Types

Resolved: I made a mistake by trying to deconstruct an object in Object.assign instead of just passing the object. Thanks to the assistance from @Eldar and @Akxe, I was able to see my error in the comments. Issue: I'm facing a problem with creating a ...

Using Vue.js 3 and Bootstrap 5 to Create a Custom Reusable Modal Component for Programmatically Showing Content

Trying to develop a reusable Modal Component using Bootstrap 5, Vuejs 3, and composible API. I have managed to achieve partial functionality, Provided (Basic Bootstrap 5 modal with classes added based on the 'show' prop, and slots in the body a ...

Incorporate a fresh attribute to the JSON data in an Angular API response

I'm currently working on updating my JSON response by adding a new object property. Below is an example of my initial JSON response: { "products": [{ "id": 1, "name": "xyz" }] } My goal is to include a new object property ca ...