typescript typeof
时间: 2023-09-24 08:14:11 浏览: 69
The `typeof` keyword in TypeScript is used to get the type of a value or a variable at runtime. It is similar to the `typeof` operator in JavaScript, but with added support for type annotations and type inference.
For example, consider the following code:
```typescript
const x = 42;
const y = "hello";
console.log(typeof x); // "number"
console.log(typeof y); // "string"
```
Here, the `typeof` operator is used to get the types of the variables `x` and `y` at runtime.
In TypeScript, `typeof` can also be used with type annotations and type inference to create more type-safe code. For example:
```typescript
function getLength(str: string) {
return str.length;
}
const message = "hello";
const length = getLength(message);
console.log(length); // 5
console.log(typeof length); // "number"
```
Here, the `getLength` function takes a string parameter and returns its length. The `typeof` keyword is used to infer the type of the `length` variable, which is `number`. This ensures that we don't accidentally try to use `length` as a string or some other type later on in our code.
阅读全文