1/* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15/**--- 16 description: > 17 A class with type parameters is called a generic class. 18 module: ESNext 19 isCurrent: true 20 ---*/ 21import { Assert } from '../../../../suite/assert.js' 22 23class MyClass<T> { 24 field: T; 25 constructor(field: T) { 26 this.field = field; 27 } 28 public getFieldName(): T { 29 return this.field; 30 } 31} 32class Compute { 33 constructor(public num1: number, public num2: number) { } 34 public hypot() { 35 return Math.sqrt(this.num1 * this.num1 + this.num2 * this.num2); 36 } 37} 38let mc1: MyClass<string> = new MyClass<string>("a"); 39Assert.equal("a", mc1.field); 40Assert.equal("a",mc1.getFieldName()); 41let mc2: MyClass<number> = new MyClass<number>(1); 42Assert.equal(1, mc2.field); 43Assert.equal(1,mc2.getFieldName()); 44let mc3: MyClass<boolean> = new MyClass<boolean>(false); 45Assert.equal(false, mc3.field); 46Assert.equal(false,mc3.getFieldName()); 47let p: Compute = new Compute(8, 6); 48let mc4: MyClass<Compute> = new MyClass<Compute>(p); 49Assert.equal(8, mc4.field.num1); 50Assert.equal(6, mc4.field.num2); 51Assert.equal(10,mc4.field.hypot()); 52 53let obj: object = { 54 x: 1, 55 y: 2 56} 57let mc5: MyClass<object> = new MyClass<object>(obj); 58Assert.equal(obj, mc5.field); 59let list: Array<number> = [1, 2, 3]; 60let mc6: MyClass<Array<number>> = new MyClass<Array<number>>(list); 61Assert.equal(list, mc6.field);