- Mastering TypeScript 3
- Nathan Rozentals
- 520字
- 2021-07-02 12:42:59
Instantiating generic classes
To use an instance of this generic class, we need to construct the class and tell the compiler via the < > syntax what the actual type of T is. We can use any type for the type of T in this generic syntax, including base types, classes, or even interfaces. Let's create a few versions of this class, as follows:
var stringConcat = new Concatenator<string>(); var numberConcat = new Concatenator<number>();
Notice the syntax that we have used to instantiate the Concatenator class. On the first line of this sample, we create an instance of the Concatenator generic class, and specify that it should substitute the generic type, T, with the type string in every place where T is being used within the code. Similarly, the second line of this sample creates an instance of the Concatenator class, and specifies that type number should be used wherever the code encounters the generic type T.
If we use this simple substitution principle, then, for the stringConcat instance (which uses strings), the inputArray argument must be of type Array<string>. Similarly, the numberConcat instance of this generic class uses numbers, and so the inputArray argument must be an array of numbers. To test this theory, let's generate an array of strings and an array of numbers, and see what the compiler says if we try to break this rule:
var stringArray: string[] = ["first", "second", "third"]; var numberArray: number[] = [1, 2, 3]; var stringResult = stringConcat.concatenateArray(stringArray); var numberResult = numberConcat.concatenateArray(numberArray); var stringResult2 = stringConcat.concatenateArray(numberArray); var numberResult2 = numberConcat.concatenateArray(stringArray);
Our first two lines define our stringArray and numberArray variables to hold the relevant arrays. We then pass in the stringArray variable to the stringConcat function—no problems there. On our next line, we pass the numberArray to the numberConcat—still okay.
Our problems, however, start when we attempt to pass an array of numbers to the stringConcat instance, which has been configured to only use strings. Again, if we attempt to pass an array of strings to the numberConcat instance, which has been configured to allow only numbers, TypeScript will generate errors as follows:
error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string[]'. Type 'number' is not assignable to type 'string'. error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'number[]'. Type 'string' is not assignable to type 'number'.
Clearly, we are attempting to pass an array of numbers where we should have used strings, and vice versa. Again, the compiler warns us that we are not using the code correctly, and forces us to resolve these issues before continuing.