When I define a type in TypeScript, it displays "any" instead

Imagine a scenario where we have a basic abstract class that represents a piece in a board game such as chess or checkers.

export abstract class Piece<Tags, Move, Position = Vector2> {
  public constructor(public position: Position, public tags = null) {}
  public abstract getMoves(board: Board<Tags, Move, Position>): Move[]
}

Furthermore, the Board class is also an abstract class.

export abstract class Board<Tags, Move, Position = Vector2> {
  public constructor(
    public size: Position,
    public pieces: Piece<Tags, Move, Position>[]
  ) {}
}

However, when attempting to extend this class, Typescript indicates that the board parameter in the getMoves method is of type any.

class Checker extends Piece<Tags, Move> {
  getMoves(board /*← any 😢*/) {
    return []
  }
}

This raises the question - could there be a misunderstanding about generics or abstract classes?

Answer №1

To demonstrate compliance with the abstract class, you must define a method with matching signature.

class Checker extends Piece<Tags, Move> {
  public getMoves(board: Board<Tags, Move, Position>): Move[]{
    return []
  }
}

Once this is done, you can instantiate a

const piece:Piece = new Checker()
and utilize type safety when invoking piece.getMoves(board).

This example illustrates the basic structure (excluding unimplemented types)...

https://i.sstatic.net/Hgljv.png

Answer №2

This topic is not related to generics.

For example, when you create a simple function without specifying the argument type, it defaults to any

function test(arg) {
// arg is of type any
}

Another issue to note is that TypeScript does not support contextually typing for overridden members. This means you have to re-list all arguments and types in the child-class.
see Consider contextually typing class member functions by their base class/interface members #1373

Answer №3

Typescript allows for method overloading. The reason the compiler cannot determine the argument type is because developers can define multiple method signatures:

class Checker extends Piece<Tags, Move> {

  getMoves():Move[];
  getMoves(x: number):Move[];
  getMoves(board: Board<Tags, Move, Position>):Move[];
  getMoves(board: any):Move[] {
    return [];
  }
}

Therefore, it becomes necessary to explicitly specify the method signature in your implementation.

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

Angular Firebase Email Verification sent to an alternate email address

I am facing a challenge with my website that only accepts emails from a specific domain, such as a university domain. Users who want to sign up using Facebook or Google need to verify their university email, but I am struggling to find a way to send the ve ...

Tips for validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

Reasons why a functional component may not trigger a rerender after a state change using useReducer()

When using react Hooks, specifically useReducer, I found that although the state changes, the functional component does not rerender. Additionally, when trying to open the drawer by pressing a button in the menu, even though the state changes the drawer re ...

Angular 17 isn't notifying child component of signal changes

In the statistics module, I have a signal that specifies the type of charts to display and this signal is updated through a radio button group. The signal: typeSignal = signal<string>('OIA') The radio buttons for setting the : <div clas ...

Ways to streamline the type from typeof T down to T

One important aspect of my function is its signature, which looks like the following. waitMessage<T extends IIPCMessagesConstructors>(wantedMessageType: T): Promise<// ?? //> The definition of IIPCMessagesConstructors is crucial and consists ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Form remains unchanged after manipulation in callback

Currently, I have a form with a list of editable objects (constants). Previously, it was possible to delete any object without confirmation. Now, I want to add a ngBootbox confirm step before the deletion process. In my .ts file, the code for deleting an ...

Ionic - Retrieve data from a Universal Resource Identifier

When using my application, users have the option to select and crop images using Ionic Native - Crop. Once they have cropped their image, I will receive the URI of the image, for example: file:///storage/emulated/0/Android/data/com.myApp/cache/15353694789 ...

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

How can I assign a specific class to certain elements within an *ngFor loop in Angular?

I have a situation where I am utilizing the *ngFor directive to display table data with the help of *ngFor="let record of records". In this scenario, I am looking to assign a custom CSS class to the 'record' based on specific conditions; for exam ...

Issues occur during installation of Angular on Mac Catalina, encountering errors while trying to run the installation command for Angular: `% sudo npm

My npm version is 6.14.6 and node version is v12.18.3. I have attempted the following: Added sudo in the beginning, but still not working. Tried to install har-validator using command: sudo npm install har-validator Attempted: npm install --force expo-cli ...

The functionality of the System JS map is not functioning properly

Despite the challenges I face with System.js, I find it to be a valuable tool that I prefer over alternatives. This is my current System.js configuration: System.config({ packages: { app: { format: 'register' ...

How can we implement type guarding for a generic class in TypeScript?

Implementing a generic class in TypeScript that can return different types based on its constructor parameter. type Type = 'foo' | 'bar'; interface Res { 'foo': {foo: number}; 'bar': {bar: string}; } class ...

I'm experiencing difficulties in establishing a connection from Ionic to my remote database

I set up a database on Fauxten and now I'm trying to connect it to my project. Although I can open the link in my browser, nothing happens when I try to call it in the app. I can't figure out what I'm missing. import { Injectable } from &ap ...

What is the best way to detect object changes in typescript?

Having an object and the desire to listen for changes in order to execute certain actions, my initial approach in ES6 would have been: let members = {}; let targetProxy = new Proxy(members, { set: function (members, key, value) { console.log(k ...

(angular 8) Error occurred when converting a file or image to FormData due to an invalid value (Note: FormData object printed as Object Form{})

I encountered an issue where I am getting an invalid value from form data. The value appears correct in `this.fileData` with a size of 5701, but becomes empty when converted to form data - `{}` is logged when I console.log the form data. Additionally, acce ...

Comparing dates in Angular 6 can be done by using a simple

Just starting with angular 6, I have a task of comparing two date inputs and finding the greatest one. input 1 : 2018-12-29T00:00:00 input 2 : Mon Dec 31 2018 00:00:00 GMT+0530 (India Standard Time) The input 1 is retrieved from MSSQL database and the in ...

What is the significance of static constants?

In my TypeScript project, I'm working on creating a constants file that will provide an Opaque token object when ServiceConstants.AUTH_SERVICE_TOKEN is called. I've experimented with two approaches: Using ServiceConstants.ts as a namespace exp ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Will the component re-render before executing the next lines when using setState or dispatch with the useReducer hook?

Upon using the useState and useReducer hooks, I encountered an issue where any code lines following the state update function (setState, dispatch) would be executed in the subsequent re-rendering, with the previous state intact before the update. Essential ...