Skip to content

Suggestion: Implements "STRUCT" rather than "INTERFACES" for types! #22101

@cacothi

Description

@cacothi

TypeScript Version: 2.7.0

Search Terms: interface, struct

Suggestion

It's confusing using interface to implement Types. As Typescript already allow us to use interface to ensure classes implements methods, and also check if the class had implemented that interface, it would be clearer if we could have a Struct for this purpose and leaving Interface for only restricting classes implementation.

Based on C# documentation I fond the following descriptions:

Struct:
A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory.

Interface:
An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.

Expected behavior:

struct CarModel {
  name: string;
  year: number;
}

const carModel: CarModel = {
  name: 'VW',
  year: 2018
}

Actual behavior:

interface CarModel {
  name: string;
  year: number;
}

const carModel: CarModel = {
  name: 'VW',
  year: 2018
}

it also allow to create interface to restrict classes implementation

interface Vehicle {
  accelerate(): void;
  currentSpeed(): number;
}

class Car implements Vehicle {
  accelerate(): void {
    //Vehicle forces implementing the method 
  }

  currentSpeed(): number{
    //Vehicle forces implementing the method 
  }
}

Reference:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/struct
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript vision

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions