[英]Typescript - How the class instance is created here please?
I have some code here. 我这里有一些代码。 My problem is that I don't manage to understand the way the instance is created. 我的问题是我无法理解实例的创建方式。 Why we use " : Calculator" ( line 3 ) to use after " new Calculator" (line 4). 为什么我们在“ new Calculator”(第4行)之后使用“:Calculator”(第3行)。 There is a difference ? 它们是有区别的 ? I know that I have a problem concerning Typescript but I found this code piece while I was looking for testing in Angular. 我知道我有一个关于Typescript的问题,但是当我在Angular中进行测试时发现了这段代码。 Also I searched into some tutorials but I don't find explanation. 我也搜索了一些教程,但没有找到解释。
import { Calculator } from './calculator';
describe('Calculator', () => {
let calculator: Calculator;
beforeEach(() => {
calculator = new Calculator();
});
});
Your "calculator.ts" file probably has something like: 您的“ calculator.ts”文件可能具有以下内容:
export class Calculator {
...
}
When you do import { Calculator } from './calculator';
当您import { Calculator } from './calculator';
, you import the Calculator class in your current file. ,您可以在当前文件中导入Calculator类。
let calculator: Calculator;
will declare a variable calculator
giving it a type Calculator
<- So you specifically say that you will have Calculator
objects in this variable. 会声明一个变量calculator
并为其赋予类型为Calculator
<-。因此,您专门说您将在此变量中包含Calculator
对象。 This is for Typescripts understanding and code completion, 这是为了理解打字稿和完成代码,
This will create a new instance of the class. 这将创建该类的新实例。
calculator = new Calculator();
In short, you use the : Calculator to give a type to that variable, on the other hand it is declared outside beforeEach's scope so it can be accesible on the tests. 简而言之,您可以使用:计算器为该变量提供类型 ,另一方面,它在beforeEach范围之前声明,因此可以在测试中使用。
If you did 如果你做了
beforeEach(() => {
let calculator = new Calculator();
});
calculator won't be accessible. 计算器将无法访问。
import { Calculator } from './calculator'; // importing Calculator class
describe('Calculator', () => { // Describing feature in BDD manner
let calculator: Calculator;
// Declaring variable calculator so it's accessible within whole describe() block
beforeEach(() => { // This hook will be called before each test in your feature
calculator = new Calculator();
// and therefore will create new instance of a Calculator for each test
});
// Here you probably will see something like
it('should return sum of 2 numbers', () => {
const result = calculator.add(2,3); // actual instance used
expect(result).toEqual(5);
});
});
第3行表示变量的类型声明,但起初是未定义的,因此您需要创建该类型的新实例,这就是为什么在下一行中它要执行new Calculator()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.