What is the use and thinking of TypeScript's Generics?

Asked 2 years ago, Updated 2 years ago, 148 views

I came to the Generics after reading the TypeScript documentation, but I am not sure what it is, so I ask you a question.
(Don't you understand the difference or benefit from the interface in ActionScript 3?)Is it similar or completely different?)

For example, if you use Generics in TypeScript to write a process that adds a number to the _allLength variable,

var_allLength=0;

interfaceSomeItem{
  getLength(): number;
}

function addLength<TextendsSomeItem>(x:T){
  _allLength=_allLength+x.getLength();
}

I think it will look like (please let me know if it's wrong)
In ActionScript 3, if you do something similar, you define the interface and receive the interface as follows.

// Interface definition (as3)
public interface ISomeItem{
    function getLength(): int
}

public var_allLength: int = 0;

// Receive and process Interface (as3)
public function addLength (item:ISomeItem): int{
    _allLength=_allLength+item.getLength();
}

I think these results will be the same, but I'm not sure if it's the right way to use Generics or if it's okay to think like this, so I posted it here

Thank you for your cooperation

typescript actionscript

2022-09-30 20:11

1 Answers

(Don't you understand the difference or benefit from the interface in ActionScript 3?)Is it similar or completely different?)

I don't understand ActionScript, but in general, the interface and generics are completely different.

As I imagine, if ActionScript does not have a function equivalent to generics, it seems that it is faster to understand it in a language manual that has generics, away from ActionScript.
Still, if you dare mention ActionScript features similar to generic, I think they are Vector type parameters.

  • In ActionScript, Vector.<T> indicates a Vector whose element is type T.
  • TypeScript indicates an array of T-type elements with Array<T> (or T[]).
    This is a prime example of generics.

You don't need to use generic for example questions, just take the same interface-type arguments as the ActionScript code example.

 // To return the value to the ActionScript example, a return is required, and the numeric type is number.
function addLength (x:SomeItem): number {
    return_allLength+=x.getLength()
}

I think it's a good idea to refer to books and other things, but the simplest example is a function that returns arguments exactly as they are in the official document.

function identity<T>(arg:T):T{
    return arg
}

Even in such a simple case, without generics, one of the following would be required:

  • Code to discard the benefits of compilation type checking (using any or cast)
  • Runtime Type Check
  • Large-volume implementation with only different types

Conversely, if you are struggling to do any of the above, you may feel comfortable using generic.


2022-09-30 20:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.