web前端typesicript面试题
时间: 2025-05-10 21:39:00 浏览: 11
### 关于 Web 前端和 TypeScript 的面试题目
#### JavaScript 中处理异步操作的方式
在 JavaScript 中,有多种方法可以用来处理异步操作。常用的方法包括回调函数、`Promise` 和 `async/await` 等[^1]。
```javascript
// 使用 Promise 处理异步请求
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// 使用 async/await 处理同样的异步请求
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
```
#### TypeScript 中的 `keyof` 关键字
TypeScript 提供了 `keyof` 类型运算符来获取对象属性名的联合类型。这使得开发者可以在编译时确保对对象键的操作是类型安全的[^2]。
```typescript
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person; // "name" | "age"
```
#### TypeScript 中的类型保护机制
类型保护是一种用于缩小类型的语法结构,在特定条件下使某些变量具有更具体的类型。常见的实现方式包括使用 `typeof`、`instanceof` 或者自定义类型谓词。
```typescript
function isString(value: any): value is string {
return typeof value === 'string';
}
function example(x: string | number) {
if (isString(x)) {
// 在这个分支里, x 被视为字符串类型
console.log(x.toUpperCase());
} else {
// 否则, x 是数字类型
console.log(x + 1);
}
}
```
#### Cookie 的有效期及其作用域
Cookie 可以设置一个过期时间,在此之前 cookie 将保持有效,即使用户关闭了浏览器窗口或重启计算机。通过这种方式,数据能够在客户端持久化存储一段时间,并可用于后续的数据交换和服务端通信[^3]。
```http
Set-Cookie: sessionId=abc123; Expires=Tue, 1 Jan 2024 00:00:00 GMT; Path=/; HttpOnly
```
阅读全文
相关推荐















