You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/project/declarationspaces.md
+33Lines changed: 33 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -47,4 +47,37 @@ var bar: foo; // ERROR: "cannot find name 'foo'"
47
47
```
48
48
The reason why it says `cannot find name` is because the name `foo`*is not defined* in the *type* declaration space.
49
49
50
+
### TIPS
51
+
52
+
#### Copying Stuff around in the Type Declaration Space
53
+
54
+
If you want to move a class around you might be tempted to do the following:
55
+
56
+
```ts
57
+
classFoo { }
58
+
var Bar =Foo;
59
+
var bar:Bar; // ERROR: "cannot find name 'Bar'"
60
+
```
61
+
This is an error because `var` only copied the `Foo` into the *variable* declaration space and you therefore cannot use `Bar` as a type annotation. The proper way is to use the `import` keyword. Note that you can only use the `import` keyword in such a way if you are using *namespaces* or *modules* (more on these later):
62
+
63
+
```ts
64
+
namespaceimporting {
65
+
exportclassFoo { }
66
+
}
67
+
68
+
importBar=importing.Foo;
69
+
var bar:Bar; // Okay
70
+
```
71
+
72
+
#### Capturing the type of a variable
73
+
74
+
You can actually use a variable in a type annotation using the `typeof` operator. This allows you to tell the compiler that one variable is the same type as another. Here is an example to demonstrate this:
75
+
76
+
```ts
77
+
var foo =123;
78
+
var bar:typeoffoo; // `bar` has the same type as `foo` (here `number`)
79
+
bar=456; // Okay
80
+
bar='789'; // ERROR: Type `string` is not `assignable` to type `number`
0 commit comments