0%

typeof

typeof

typeof 在类型上下文中使用,用于获取一个变量或者属性的类型,只能对标识符和属性使用

1
2
let s="hello";
let n:typeof s;//let n:string
1
2
let shouldContinue:typeof msgbox("hello");
//',' expected.

要获取msgbox(“hello”)返回值的类型,正确写:

1
ReturnType<typeof msgbox>

ReturnType

你传入一个函数类型,ReturnType会返回该函数的返回值的类型

1
2
type Predicate=(x:unknown)=>boolean;
type K=ReturnType<Predicate>;//type K=boolean

值(values)和类型(types)并不是一种东西,为了获取值f也就是函数f的类型,需要使用typeof,而ReturnType,T必须是一个类型

1
2
3
4
5
6
7
8
9
function f(){
return {x:10,y:3};
}
type P=ReturnType<f>;// 'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?
type P=ReturnType<typeof f>
// type P = {
// x: number;
// y: number;
// }

对enum类型使用typeof

在TypeScript中,在具体运行时,enum类型会被编译成对象

1
2
3
4
enum UserResponse {
No=0,
Yes=1,
}

对应编译的JavaScript

1
2
3
4
5
var UserResponse;
(function (UserResponse) {
UserResponse[UserResponse["No"] = 0] = "No";
UserResponse[UserResponse["Yes"] = 1] = "Yes";
})(UserResponse || (UserResponse = {}));
1
2
3
4
5
6
7
8
console.log(UserResponse);

// [LOG]: {
// "0": "No",
// "1": "Yes",
// "No": 0,
// "Yes": 1
// }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
type result = typeof UserResponse;

// ok
const a: result = {
"No": 2,
"Yes": 3
}

result 类型类似于:

// {
// "No": number,
// "YES": number
// }

一般搭配keyof用于获取属性名的联合字符串

1
type result=keyof typeof UserResponse;

参考:

https://ts.yayujs.com/handbook/TypeofTypeOperator.html#%E5%AF%B9-enum-%E4%BD%BF%E7%94%A8-typeof

https://www.typescriptlang.org/docs/handbook/2/typeof-types.html