File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed
docs/documentation/zh/handbook-v2/Type Manipulation Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ title : Typeof 类型运算符
3
+ layout : docs
4
+ permalink : /zh/docs/handbook/2/typeof-types.html
5
+ oneline : " 在类型上下文中使用 typeof 类型运算符。"
6
+ translatable : true
7
+ ---
8
+
9
+ ## ` typeof ` 类型运算符
10
+
11
+ JavaScript 已经有了一个 ` typeof ` 运算符,你可以在 _ 表达式_ 上下文中使用:
12
+
13
+ ``` ts twoslash
14
+ // 打印出 "string"
15
+ console .log (typeof " Hello world" );
16
+ ```
17
+
18
+ TypeScript 添加了一个 ` typeof ` 运算符,让您可以在 _ 类型_ 上下文中使用它来引用变量或属性的 _ 类型_ :
19
+
20
+ ``` ts twoslash
21
+ let s = " hello" ;
22
+ let n: typeof s ;
23
+ // ^?
24
+ ```
25
+
26
+ 这对于基本类型不是很有用,但结合其他类型运算符,您可以使用 ` typeof ` 方便地表示出多种形式。
27
+ 例如,让我们从预定义类型 ` ReturnType<T> ` 开始查看。它接受一个 _ 函数类型_ 并生成函数的返回类型:
28
+
29
+ ``` ts twoslash
30
+ type Predicate = (x : unknown ) => boolean ;
31
+ type K = ReturnType <Predicate >;
32
+ // ^?
33
+ ```
34
+
35
+ 如果我们尝试在函数名上使用 ` ReturnType ` ,我们会看到一个指导性错误:
36
+
37
+ ``` ts twoslash
38
+ // @errors: 2749
39
+ function f() {
40
+ return { x: 10 , y: 3 };
41
+ }
42
+ type P = ReturnType <f >;
43
+ ```
44
+
45
+ 请记住,_ values_ 和 _ types_ 不是一回事。要引用函数 ` f ` 值的类型,我们使用 ` typeof ` :
46
+
47
+ ``` ts twoslash
48
+ function f() {
49
+ return { x: 10 , y: 3 };
50
+ }
51
+ type P = ReturnType <typeof f >;
52
+ // ^?
53
+ ```
54
+
55
+ ### 限制
56
+
57
+ TypeScript 有意限制了可以使用 ` typeof ` 表达式的种类。
58
+
59
+ 具体来说,仅在标识符(即变量名)或其属性上使用 ` typeof ` 是合法的。
60
+ 这有助于避免编写出你认为正在执行但实际并没有执行,让人迷惑的代码陷阱:
61
+
62
+ ``` ts twoslash
63
+ // @errors: 1005
64
+ declare const msgbox: () => boolean ;
65
+ // type msgbox = any;
66
+ // ---cut---
67
+ // 以为等同于 ReturnType<typeof msgbox>,实际是错误的
68
+ let shouldContinue: typeof msgbox (" Are you sure you want to continue?" );
69
+ ```
You can’t perform that action at this time.
0 commit comments