What is the procedure for utilizing the Type Checker to obtain an Interface or Class that extends a

Here is an example code snippet:

class Animal {
    name: string;
}

class Dog extends Animal {
    breed: string;
}

interface DataProps {
    color?: string;
}

interface DogProps extends DataProps {
    type?: "Beagle" | "Sheepdog";
}

When using Class extends, you can check the names like this:

const symbol = this.checker.getSymbolAtLocation((<ts.ClassDeclaration> node).name);
const extendsDocEntry = "declarations" in symbol? symbol.declarations.map((declaration: any) => (
    "expression" in declaration && declaration.expression.text
)).filter((extendsName: any) => extendsName) : void 0;

I am not entirely sure if this code is correct, and I am also unsure how to retrieve Interface extends.

If anyone can help me solve this problem, I would greatly appreciate it.

Answer №1

When examining the ts.ClassLikeDeclaration, you will notice a heritageClauses property. This property will always have a defined value and will consist of an array of objects that are classified as ts.HeritageClause.

For each heritage clause, you can inspect the token property to determine if it matches either ts.SyntaxKind.ExtendsKeyword or ts.SyntaxKind.ImplementsKeyword. Subsequently, you can explore the types property to access all the expressions with type arguments.

After obtaining the expression and type arguments, you can utilize

this.checker.getSymbolAtLocation(...)
to retrieve the symbol of the extension or
this.typeChecker.getTypeAtLocation(...)
to obtain the type.

Below is a basic, untested code snippet to help you initiate the process... it is recommended to iterate over these arrays and validate heritageClause.token as explained earlier:

const classDeclaration = node as ts.ClassDeclaration;
const firstHeritageClause = classDeclaration.heritageClauses![0];
const firstHeritageClauseType = firstHeritageClause.types![0];

const extendsSymbol = this.checker.getSymbolAtLocation(firstHeritageClauseType.expression);
const extendsType = this.checker.getTypeAtLocation(firstHeritageClauseType.expression);

Regarding ts.InterfaceDeclaration, the methodology remains consistent. It also includes an array named heritageClauses.

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 in TypeScript to prevent the modification of a class property and still trigger a runtime error if attempted?

I currently have the following code snippet: class Computed<Value> { _value: Value; get value(){ return this._value; } } When attempting to set the value property, TypeScript returns an error message: Cannot assign to value because it is ...

Update gulp configuration to integrate TypeScript into the build process

In the process of updating the build system for my Angular 1.5.8 application to support Typescript development, I encountered some challenges. After a complex experience with Grunt, I simplified the build process to only use Gulp and Browserify to generat ...

The key is not applicable for indexing the type as expected

Here is the TS code I am working with: type Fruit = { kind: "apple" } | { kind: "grape"; color: "green" | "black" }; type FruitTaste<TFruit extends Fruit> = TFruit["kind"] extends "apple" ? "good" : TFruit["color"] extends "green" ? "good" : ...

An issue arises when trying to group and sum an array of objects due to difficulty converting strings to arrays in TypeScript

Below is the provided code snippet: Definition of Interface - interface IWEXInterface { readonly Date?: string; "Exec Qty"?: string; readonly Expiry?: string; } Data Collection - let data: IWEXInterface[] = [ { Date: &qu ...

Issue with bundling project arises post upgrading node version from v6.10 to v10.x

My project uses webpack 2 and awesome-typescript-loader for bundling in nodejs. Recently, I upgraded my node version from 6.10 to 10.16. However, after bundling the project, I encountered a Runtime.ImportModuleError: Error: Cannot find module 'config ...

Angular2 Navigation Menu

I have a side bar and I want its children to appear when the user clicks on the parent. For example, clicking on LinkTest should display its corresponding content as block. You can check out the Angular and Typescript code snippet at this link: http://jsfi ...

Node.js and mongoose provide a powerful tool for filtering documents dynamically by leveraging a variable that is dependent on another document. Want to learn

I've hit a bit of a roadblock here... I'm trying to add a new property to a document that will change based on the values in that document as well as another document. Let me provide an example to clarify. First, I have a Candidate Schema: const ...

"Null value is no longer associated with the object property once it has

What causes the type of y to change to string only after the destruction of the object? const obj: { x: string; y: string | null } = {} as any const { x, y } = obj // y is string now ...

What is the method for defining functions that accept two different object types in Typescript?

After encountering the same issue multiple times, I've decided it's time to address it: How can functions that accept two different object types be defined in Typescript? I've referred to https://www.typescriptlang.org/docs/handbook/unions ...

Jest does not support the processing of import statements in typescript

I am attempting to execute a simple test. The source code is located in src/index.ts and contains the following: const sum = (a, b) => {return a+b} export default sum The test file is located in tests/index.test.ts with this code: impor ...

Why does Angular CLI create "spec.ts" files?

My current go-to tool for generating and serving projects is Angular CLI. So far, it's been pretty smooth sailing – although I've noticed that for my smaller learning projects, it tends to create more than what I actually need. But hey, that&ap ...

typescript: declaring types in a separate JavaScript file

Imagine you have a JavaScript library that exports some types for use (let's call it js1.js). You also have some TypeScript code sitting in a <script type="module"> tag that you want to use these types with (let's say ts1.ts). To make this ...

Is it possible to use string indexes with jQuery each method in Typescript?

When running a jQuery loop in Typescript, I encountered an issue where the index was being reported as a string. $.each(locations, (index, marker) => { if(this.options && this.options.bounds_marker_limit) { if(index <= (this.opt ...

Guide on how to create a custom response using class-validator in NestJS

Is it feasible to customize the error response generated by class-validator in NestJs? The default error message structure in NestJS looks like this: { "statusCode": 400, "error": "Bad Request", "message": [ { "target": {} ...

What is the method for verifying the types of parameters in a function?

I possess two distinct interfaces interface Vehicle { // data about vehicle } interface Package { // data about package } A component within its props can receive either of them (and potentially more in the future), thus, I formulated a props interface l ...

CdkVirtualFor does not display any content

I'm facing an issue with implementing cdk-virtual-scroll in my chat application. Unfortunately, it's not showing anything on the screen. Strangely, when I resort to using the regular "ngFor", everything works smoothly. However, as soon as I switc ...

Generate dynamic forms utilizing JSON data

I am in the process of developing an application that enables users to answer questions about themselves. The questions are being retrieved from an API. My next step is to generate a form with these questions as entry fields. I am currently utilizing a met ...

Struggling to retrieve variable within the .catch function in Ionic 3

I am having trouble accessing the toast variable from the constructor in order to toast errors. It keeps showing as undefined, and I'm not sure why. This issue seems to only occur in this class, which is strange. The error message reads "ERROR TypeErr ...

Is it possible for a TypeScript function to be used as a React prop even if it conflicts with the function signature's in

Why does the TypeScript type checker allow a prop with a function parameter that does not strictly match the definition? For example, I have a function called callbackImpl = (str: string): number, which is passed as a React prop parameter defined as callb ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...