40 道Typescript 面试题及其答案与代码示例

开发 前端
在进行前端技术面试的时候,我们经常会遇到TypeScript 的一些面试题,因此,今天这篇文章,我整理汇总了40道关于TypeScript 的基础知识的面试题。

在进行前端技术面试的时候,我们经常会遇到TypeScript 的一些面试题,因此,今天这篇文章,我整理汇总了40道关于TypeScript 的基础知识的面试题。

在实际工作中,它的优势在于提高开发人员的工作效率。

今天这期内容,主要是对 TypeScript 内容的特定面试题,并提供详细的参考答案、代码示例以及相关的延伸阅读内容。

那么,我们现在就开始进入今天的内容吧。

1.什么是 TypeScript,它与 JavaScript 有何不同?提供 TypeScript 代码示例。

答案:TypeScript 是 JavaScript 的超集,为该语言添加了静态类型。它允许开发人员定义变量、函数参数和返回值的数据类型,这有助于在编译时而不是运行时捕获错误。这是一个例子:

function greet(name: string): string {
  return `Hello, ${name}!`;
}
const message: string = greet('John');
console.log(message); // Output: "Hello, John!"

延伸阅读:TypeScript 官方网站(https://www.typescriptlang.org/)

2.解释 TypeScript 中静态类型的概念及其好处。

答案:TypeScript 中的静态类型可以在开发过程中指定变量、函数参数和返回值的数据类型。这有助于及早捕获与类型相关的错误,从而提高代码质量和可维护性。

好处是拥有更好的代码文档、增强的工具支持以及提高的开发人员生产力。

延伸阅读:TypeScript 官方手册——基本类型(https://www.typescriptlang.org/docs/handbook/basic-types.html)

3.TypeScript 中的接口是什么?举个例子。

答案:TypeScript 中的接口定义了对象结构的契约,指定其属性和方法的名称和类型。它们促进强大的类型检查并实现更好的代码组织。这是一个例子:

interface Person {
  name: string;
  age: number;
}
function greet(person: Person): string {
  return `Hello, ${person.name}! You are ${person.age} years old.`;
}
const john: Person = { name: 'John', age: 30 };
const message: string = greet(john);
console.log(message); // Output: "Hello, John! You are 30 years old."

延伸阅读:TypeScript 官方手册——接口(https://www.typescriptlang.org/docs/handbook/interfaces.html)

4.使用 TypeScript 相对于纯 JavaScript 有什么好处?

答:TypeScript 提供了多种好处,包括静态类型、更好的代码分析和工具支持、改进的代码可读性、早期错误检测、更轻松的代码重构以及增强的代码文档。它还使开发人员能够编写更易于维护和扩展的应用程序。

延伸阅读:TypeScript 官方网站 — 为什么选择 TypeScript?(https://www.typescriptlang.org/docs/handbook/why-typescript.html)

5.如何在 TypeScript 的接口中定义可选属性?举个例子。

答案:您可以使用 ? 在接口中定义可选属性。属性名称后面的修饰符。可选属性可能存在于实现该接口的对象中,也可能不存在。这是一个例子:

interface Person {
  name: string;
  age?: number;
}
const john: Person = { name: 'John' };
const jane: Person = { name: 'Jane', age: 25 };

延伸阅读:TypeScript 官方手册——接口(https://www.typescriptlang.org/docs/handbook/interfaces.html)

6.解释 TypeScript 中联合类型的概念并提供示例。

答:联合类型允许一个变量有多种类型。它通过使用 | 来表示类型之间的符号。这允许变量存储任何指定类型的值。这是一个例子:

function printId(id: number | string): void {
  console.log(`ID: ${id}`);
}
printId(123); // Output: "ID: 123"
printId('abc'); // Output: "ID: abc"

延伸阅读:TypeScript 官方手册——联合类型(https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html)

7.TypeScript 中的类型断言是什么?举个例子。

答案:当无法自动推断类型时,TypeScript 中的类型断言允许您显式告诉编译器变量的类型。这是使用 <type> 或 as type 语法实现的。这是一个例子:

let length: any = '5';
let numberLength: number = <number>length; // Using <type> syntax
let stringLength: number = length as number; // Using "as type" syntax

延伸阅读:TypeScript 官方手册——类型断言(https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions)

8.如何在 TypeScript 中定义具有可选参数和默认参数的函数?举个例子。

答案:您可以使用 ? 定义带有可选参数和默认参数的函数。可选参数的修饰符以及为参数分配默认值。这是一个例子:

function greet(name: string, message: string = 'Hello', times?: number): void {
  for (let i = 0; i < (times || 1); i++) {
    console.log(`${message}, ${name}!`);
  }
}
greet('John'); // Output: "Hello, John!"
greet('Jane', 'Hi'); // Output: "Hi, Jane!"
greet('Tom', 'Hey', 3); // Output: "Hey, Tom!", "Hey, Tom!", "Hey, Tom!"

延伸阅读:TypeScript 官方手册——函数(https://www.typescriptlang.org/docs/handbook/functions.html)

9.TypeScript 中的泛型是什么?举个例子。

答案:TypeScript 中的泛型允许您创建可与各种类型一起使用的可重用组件或函数。它们支持强类型,同时保持使用不同数据类型的灵活性。这是一个例子:

function identity<T>(arg: T): T {
  return arg;
}
const result1 = identity<number>(42); // Explicitly specifying the type
const result2 = identity('hello'); // Inferring the type

延伸阅读:TypeScript 官方手册——泛型(https://www.typescriptlang.org/docs/handbook/generics.html)

10.通过示例解释 TypeScript 中的“keyof”关键字。

答案:TypeScript 中的“keyof”关键字是一个类型运算符,它返回表示对象键的文字类型的联合。它允许您对对象键执行类型安全操作。这是一个例子:

interface Person {
  name: string;
  age: number;
}
type PersonKeys = keyof Person; // "name" | "age"

延伸阅读:TypeScript 官方手册——索引类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types)

11. TypeScript 中的类型保护是什么?它们如何工作?举个例子。

答案:类型防护是 TypeScript 表达式,它在运行时检查变量的类型,并允许您根据类型执行不同的操作。它们可以实现更好的类型推断,并提供一种更有效地处理联合类型的方法。

这是使用 typeof 和 instanceof 类型保护的示例:

function printValue(value: string | number): void {
  if (typeof value === 'string') {
    console.log(`The value is a string: ${value}`);
  } else if (typeof value === 'number') {
    console.log(`The value is a number: ${value}`);
  }
}
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}
function greet(person: Person | string): void {
  if (person instanceof Person) {
    console.log(`Hello, ${person.name}!`);
  } else if (typeof person === 'string') {
    console.log(`Hello, ${person}!`);
  }
}
const stringValue: string = 'Hello';
const numberValue: number = 42;


printValue(stringValue); // Output: "The value is a string: Hello"
printValue(numberValue); // Output: "The value is a number: 42"


const john: Person = new Person('John');


greet(john); // Output: "Hello, John!"
greet('Jane'); // Output: "Hello, Jane!"

延伸阅读:TypeScript 官方手册 — Type Guards(https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards)

12.解释 TypeScript 中条件类型的概念。举个例子。

答案:TypeScript 中的条件类型允许您创建依赖于条件的类型。它们用于根据类型之间的关系执行类型推断。这是一个例子:

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function add(a: number, b: number): number {
  return a + b;
}
type AddReturnType = ReturnType<typeof add>; // number

在此示例中,ReturnType 是推断函数返回类型的条件类型。

延伸阅读:TypeScript 官方手册——条件类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)

13.TypeScript 中的映射类型是什么?举个例子。

答案:TypeScript 中的映射类型允许您通过将属性映射到新类型来基于现有类型创建新类型。它们使您能够轻松修改现有类型或向现有类型添加属性。这是一个例子:

interface Person {
  name: string;
  age: number;
}
type PersonWithOptionalProperties = { [K in keyof Person]?: Person[K] };
const john: Person = { name: 'John', age: 30 };
const johnWithOptionalProperties: PersonWithOptionalProperties = { name: 'John' };

在此示例中,PersonWithOptionalProperties 是一个映射类型,它使 Person 的所有属性都是可选的。

延伸阅读:TypeScript 官方手册 — 映射类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types)

14.解释 TypeScript 中的“部分”实用程序类型。举个例子。

答案:TypeScript 中的“部分”实用程序类型用于使现有类型的所有属性成为可选。它允许您从现有类型创建具有可选属性的新类型。这是一个例子:

interface Person {
  name: string;
  age: number;
}
type PartialPerson = Partial<Person>;
const john: PartialPerson = { name: 'John' };

在此示例中,PartialPerson 是具有来自 Person 接口的可选属性的类型。

延伸阅读:TypeScript 官方手册——实用类型(https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)

15.TypeScript 中的“只读”实用程序类型是什么?它是如何工作的?举个例子。

答案:TypeScript 中的“Readonly”实用程序类型用于使现有类型的所有属性变为只读。它可以防止对象创建后修改其属性。这是一个例子:

interface Person {
  readonly name: string;
  age: number;
}
const john: Readonly<Person> = { name: 'John', age: 30 };
john.age = 31; // Error: Cannot assign to 'age' because it is a read-only property.

在此示例中,age 属性可以修改,但 name 属性是只读的。

延伸阅读:TypeScript 官方手册——实用类型(

16.映射类型中的“键重新映射”和“值重新映射”是什么?为每个提供示例。

回答:“键重映射”和“值重映射”是 TypeScript 中映射类型的两个特性。

“键重新映射”允许您使用 as 关键字更改现有类型的键。这是一个例子:

interface Person {
  name: string;
  age: number;
}
type MappedPerson = { [K in keyof Person as `new_${K}`]: Person[K] };
const john: MappedPerson = { new_name: 'John', new_age: 30 };

在此示例中,Person 的键被重新映射为具有前缀“new_”。

“值重新映射”允许您使用条件类型更改现有类型的值。这是一个例子:

type ValueRemapped<T> = T extends 'a' ? 'x' : T extends 'b' ? 'y' : 'z';
type Result = ValueRemapped<'a' | 'b' | 'c'>; // Result: 'x' | 'y' | 'z'

在此示例中,值“a”、“b”和“c”分别重新映射为“x”、“y”和“z”。

延伸阅读:TypeScript 官方手册 — 映射类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types)

17.解释 TypeScript 中的“Pick”实用程序类型。举个例子。

答案:TypeScript 中的“Pick”实用程序类型允许您通过从现有类型中选择特定属性来创建新类型。它有助于创建现有类型的子集。这是一个例子:

interface Person {
  name: string;
  age: number;
  city: string;
}
type PersonInfo = Pick<Person, 'name' | 'age'>;
const john: PersonInfo = { name: 'John', age: 30 };

在此示例中,PersonInfo 是仅包含 Person 接口中的“name”和“age”属性的类型。

延伸阅读:TypeScript 官方手册——实用类型(https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)

18.TypeScript 中的“Omit”实用程序类型是什么?它是如何工作的?举个例子。

答案:TypeScript 中的“Omit”实用程序类型允许您通过从现有类型中排除特定属性来创建新类型。它有助于创建删除了某些属性的类型。这是一个例子:

interface Person {
  name: string;
  age: number;
  city: string;
}
type PersonWithoutCity = Omit<Person, 'city'>;
const john: PersonWithoutCity = { name: 'John', age: 30 };

在此示例中,PersonWithoutCity 是一种从 Person 接口中排除“city”属性的类型。

延伸阅读:TypeScript 官方手册——实用类型(https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)

19.TypeScript 中的“条件映射类型”是什么?举个例子。

答:条件映射类型将条件类型和映射类型结合起来,根据条件执行类型转换。它们允许您根据现有类型的属性创建动态类型。这是一个例子:

interface Person {
  name: string;
  age: number;
}
type MappedConditional<T> = {
  [K in keyof T]: T[K] extends number ? string : T[K];
};
const john: MappedConditional<Person> = { name: 'John', age: '30' };

在此示例中,MappedConditional 是一个条件映射类型,它将 Person 的数字属性转换为字符串。

延伸阅读:TypeScript 官方手册 — 映射类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)

20.条件类型中“keyof”和“in”关键字的用途是什么?举个例子。

答案:条件类型中的“keyof”关键字用于获取对象类型的键的并集。它允许您以类型安全的方式使用对象的键。“in”关键字检查属性键是否存在于从“keyof”获得的键的并集中。这是一个例子:

type CheckKey<T, K extends keyof T> = K extends 'name' ? true : false;
interface Person {
  name: string;
  age: number;
}
type IsNameKey = CheckKey<Person, 'name'>; // Result: true
type IsCityKey = CheckKey<Person, 'city'>; // Result: false

在此示例中,CheckKey 是一个条件类型,用于检查提供的键是否为“name”。

延伸阅读:TypeScript 官方手册 — keyof Type Operator、TypeScript 官方手册 — in Operator(https://www.typescriptlang.org/docs/handbook/advanced-types.html#keyof-type-operator)

21.解释 TypeScript 中的“排除”实用程序类型。举个例子。

答案:TypeScript 中的“排除”实用程序类型允许您通过从联合中排除某些类型来创建新类型。它有助于创建联合类型的子集。这是一个例子:

type Color = 'red' | 'green' | 'blue';
type PrimaryColors = Exclude<Color, 'green' | 'blue'>;
const primary: PrimaryColors = 'red'; // Okay
const invalidColor: PrimaryColors = 'green'; // Error: Type '"green"' is not assignable to type 'PrimaryColors'.

在此示例中,PrimaryColors 是一种从颜色联合中排除“绿色”和“蓝色”颜色的类型。

延伸阅读:TypeScript 官方手册——实用类型(https://www.typescriptlang.org/docs/handbook/utility-types.html#excludetype-excludedunion)

22.TypeScript 中的“模板文字类型”是什么?举个例子。

答案:TypeScript 中的模板文字类型允许您使用模板文字语法来操作类型中的字符串。它们提供了一种基于字符串模式创建复杂类型的方法。这是一个例子:

type Greeting<T extends string> = `Hello, ${T}!`;
type GreetJohn = Greeting<'John'>; // Result: "Hello, John!"
type GreetJane = Greeting<'Jane'>; // Result: "Hello, Jane!"

在此示例中,Greeting 是一个模板文字类型,它根据提供的名称生成问候语。

延伸阅读:TypeScript 官方手册——模板文字类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#template-literal-types)

23.解释条件类型中的“infer”关键字。举个例子。

答案:条件类型中的“infer”关键字用于从条件类型中的另一种类型推断出类型。它允许您捕获类型并将其分配给类型变量。这是一个例子:

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function add(a: number, b: number): number {
  return a + b;
}
type AddReturnType = ReturnType<typeof add>; // Result: number

在此示例中,ReturnType 是一个条件类型,它使用“infer”关键字推断函数的返回类型。

延伸阅读:TypeScript 官方手册——条件类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)

24.TypeScript 中的“keyof”和“typeof”关键字有何用途?为每个提供示例。

答:“keyof”关键字用于获取对象类型的键的并集,“typeof”关键字用于获取值的类型。以下是每个示例:

interface Person {
  name: string;
  age: number;
}
type PersonKeys = keyof Person; // Result: "name" | "age"
const john = { name: 'John', age: 30 };
type JohnType = typeof john; // Result: { name: string, age: number }

在第一个示例中,PersonKeys 是表示 Person 接口的键联合的类型。在第二个示例中,JohnType 是表示 john 对象类型的类型。

延伸阅读:TypeScript 官方手册 — keyof 类型运算符、TypeScript 官方手册 — typeof 类型运算符(https://www.typescriptlang.org/docs/handbook/advanced-types.html#keyof-type-operator)

25.TypeScript 中的“const 断言”是什么?举个例子。

答案:TypeScript 中的“Const 断言”允许您通知编译器特定的文字表达式应被视为文字而不是扩展类型。这是一个例子:

function getConfig() {
  const config = {
    apiUrl: 'https://api.example.com',
    timeout: 5000,
  } as const;
  return config;
}
const config = getConfig();
// config is inferred as:
// {
//   readonly apiUrl: "https://api.example.com";
//   readonly timeout: 5000;
// }

在此示例中,由于 as const 断言,config 对象被视为具有只读属性的常量对象。

延伸阅读:TypeScript官方手册——文字类型加宽(https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions)

26.TypeScript 中的“私有”和“受保护”访问修饰符是什么?为每个提供示例。

答案:“Private”和“protected”是 TypeScript 中的访问修饰符,用于控制类成员的可见性和可访问性。

class Person {
  private name: string;
  protected age: number;
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
  greet() {
    console.log(`Hello, my name is ${this.name}, and I am ${this.age} years old.`);
  }
}
class Employee extends Person {
  private salary: number;
  constructor(name: string, age: number, salary: number) {
    super(name, age);
    this.salary = salary;
  }
  showSalary() {
    console.log(`My salary is ${this.salary}.`);
  }
}
const john = new Person('John', 30);
console.log(john.name); // Error: Property 'name' is private and only accessible within class 'Person'.
console.log(john.age); // Error: Property 'age' is protected and only accessible within class 'Person' and its subclasses.
const employee = new Employee('Jane', 25, 50000);
employee.greet(); // Output: "Hello, my name is Jane, and I am 25 years old."
employee.showSalary(); // Output: "My salary is 50000."
console.log(employee.salary); // Error: Property 'salary' is private and only accessible within class 'Employee'.

在此示例中,name 属性具有“private”访问修饰符,age 属性有“protected”访问修饰符。工资属性是 Employee 类私有的。

延伸阅读:TypeScript 官方手册——类(https://www.typescriptlang.org/docs/handbook/classes.html)

27.解释 TypeScript 条件类型中的“keyof T extends K”构造。举个例子。

答案:TypeScript 条件类型中的“keyof T extends K”构造用于使用“extends”关键字根据指定条件过滤对象类型的键。这是一个例子:

type FilterProperties<T, K> = {
  [P in keyof T as T[P] extends K ? P : never]: T[P];
};
interface Person {
  name: string;
  age: number;
  email: string;
}
type StringProperties = FilterProperties<Person, string>;
// Result: {
//   name: string;
//   email: string;
// }
type NumberProperties = FilterProperties<Person, number>;
// Result: {
//   age: number;
// }

在此示例中,FilterProperties 是一个条件映射类型,它根据值类型过滤 Person 的属性。

延伸阅读:TypeScript 官方手册——条件类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)

28.TypeScript 中的“mixins”是什么?举个例子。

答案:TypeScript 中的 Mixins 允许您通过将某个类与一个或多个其他类组合来向该类添加行为。它支持代码重用和组合。这是一个 mixin 的例子:

class Printable {
  print() {
    console.log(this.toString());
  }
}
class MyObject {
  constructor(private name: string) {}
  toString() {
    return `Object: ${this.name}`;
  }
}
interface MyObject extends Printable {}
const myObj = new MyObject('example');
myObj.print(); // Output: "Object: example"

在此示例中,Printable 类充当 mixin,将 print 方法添加到 MyObject 类。

延伸阅读:TypeScript 官方手册 — Mixins(https://www.typescriptlang.org/docs/handbook/mixins.html)

29.解释 TypeScript 中“声明合并”的概念。举个例子。

回答:TypeScript 中的“声明合并”是编译器将同一实体的多个声明合并到单个定义中的过程。它允许您扩展接口、函数、类和枚举。

interface Person {
  name: string;
}
interface Person {
  age: number;
}
const john: Person = { name: 'John', age: 30 };
console.log(john); // Output: { name: 'John', age: 30 }

在此示例中,编译器将两个 Person 接口合并为一个定义,允许 john 同时具有 name 和age 属性。

延伸阅读:TypeScript官方手册——声明合并(https://www.typescriptlang.org/docs/handbook/declaration-merging.html)

30.TypeScript 中的“noUncheckedIndexedAccess”编译器选项是什么?为什么它很有用?举个例子。

答案:TypeScript 中的“noUncheckedIndexedAccess”编译器选项用于在使用索引访问属性时捕获潜在的未定义或空值。它通过避免运行时错误来帮助提高代码安全性。

// tsconfig.json
{
  "compilerOptions": {
    "noUncheckedIndexedAccess": true
  }
}

这是一个例子:

const data: { [key: string]: number } = {
  apple: 1,
  banana: 2,
};
const fruit = 'pear';
const count = data[fruit]; // Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ apple: number; banana: number; }'.

在此示例中,启用“noUncheckedIndexedAccess”会引发错误,因为 data[fruit] 可能未定义或为 null。

进一步阅读:TypeScript 编译器选项(https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess)

31.TypeScript 中的“装饰器”是什么?举个例子。

答:装饰器是 TypeScript 的一项功能,允许您修改类、方法或属性的行为。它们使用 @decoratorName 语法声明并在运行时执行。这是一个简单的类装饰器的示例:

function MyClassDecorator<T extends { new (...args: any[]): {} }>(constructor: T) {
  return class extends constructor {
    newProperty = 'decorated property';
    hello = 'overridden';
  };
}
@MyClassDecorator
class MyClass {
  hello: string;
  constructor() {
    this.hello = 'world';
  }
}
const myClassInstance = new MyClass();
console.log(myClassInstance.hello); // Output: "overridden"
console.log((myClassInstance as any).newProperty); // Output: "decorated property"

在此示例中,MyClassDecorator 函数是一个类装饰器,用于修改 MyClass 类的行为。

延伸阅读:TypeScript 官方手册——装饰器(https://www.typescriptlang.org/docs/handbook/decorators.html)

32.解释 TypeScript 中的“abstract”关键字。举个例子。

答:TypeScript 中的“abstract”关键字用于定义抽象类和方法。抽象类不能直接实例化;它们只能被延长。抽象方法在抽象类中没有实现,必须在派生类中实现。这是一个例子:

abstract class Shape {
  abstract area(): number;
}
class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }
  area(): number {
    return Math.PI * this.radius ** 2;
  }
}
const circle = new Circle(5);
console.log(circle.area()); // Output: 78.53981633974483

在此示例中,Shape 类是一个具有抽象方法 area() 的抽象类。Circle 类扩展了 Shape 类并实现了 area() 方法。

延伸阅读:TypeScript官方手册——抽象类(https://www.typescriptlang.org/docs/handbook/classes.html#abstract-classes)

33.什么是 TypeScript 中的“条件类型”,它们为什么有用?举个例子。

答案:TypeScript 中的条件类型允许您根据条件执行类型转换。它们使您能够创建依赖于其他类型之间关系的动态类型。这是一个例子:

type IsString<T> = T extends string ? true : false;
type CheckString = IsString<string>; // Result: true
type CheckNumber = IsString<number>; // Result: false

在此示例中,IsString 条件类型检查提供的类型是否为字符串。

当您想要基于其他值的类型创建类型安全的映射或过滤器时,条件类型非常有用。

延伸阅读:TypeScript 官方手册——条件类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)

34.TypeScript 中属性的“只读”修饰符是什么?举个例子。

答案:TypeScript 中的“readonly”修饰符用于使类或接口的属性变为只读,这意味着它们的值一旦设置就无法更改。这是一个例子:

class Person {
  readonly name: string;
  constructor(name: string) {
    this.name = name;
  }
}
const john = new Person('John');
console.log(john.name); // Output: "John"
john.name = 'Jane'; // Error: Cannot assign to 'name' because it is a read-only property.

在此示例中,Person 类的 name 属性被标记为只读。

延伸阅读:TypeScript 官方手册——类(https://www.typescriptlang.org/docs/handbook/classes.html#readonly-modifier)

35.解释 TypeScript 中的“as const”断言。举个例子。

答案:TypeScript 中的“as const”断言用于推断数组和对象的文字类型。它告诉编译器该值应被视为常量,而不是扩展到其基本类型。这是一个例子:

const fruits = ['apple', 'banana'] as const;
const person = {
  name: 'John',
  age: 30,
} as const;
// The type of fruits is: readonly ["apple", "banana"]
// The type of person is: {
//   readonly name: "John";
//   readonly age: 30;
// }

在此示例中,fruits 数组和 person 对象的类型分别被推断为只读元组和对象。

延伸阅读:TypeScript 官方手册——文字类型(https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions)

36.TypeScript 中的“模块增强”是什么?举个例子。

答案:TypeScript 中的模块扩充允许您在外部模块中添加新声明或扩展现有声明。当您想要向第三方库添加功能时,它非常有用。这是一个例子:

// Original module in a third-party library
// external-library.d.ts
declare module 'external-library' {
  export function greet(name: string): string;
}
// Augment the module
// augmentations.d.ts
declare module 'external-library' {
  export function goodbye(name: string): string;
}
// Usage
import { greet, goodbye } from 'external-library';
console.log(greet('John')); // Output: "Hello, John!"
console.log(goodbye('John')); // Output: "Goodbye, John!"

在此示例中,我们通过添加 goodbye 函数来增强“external-library”模块。

延伸阅读:TypeScript 官方手册——模块增强(https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)

37.TypeScript 中的“keyof”运算符有何用途?举个例子。

答案:TypeScript 中的“keyof”运算符用于获取对象类型的键的并集。它允许您以类型安全的方式使用对象的键。这是一个例子:

interface Person {
  name: string;
  age: number;
}
type PersonKeys = keyof Person; // Result: "name" | "age"

在此示例中,PersonKeys 是表示 Person 接口的键的并集的类型。

延伸阅读:TypeScript官方手册——keyof类型运算符(https://www.typescriptlang.org/docs/handbook/advanced-types.html#keyof-type-operator)

38.TypeScript 中“typeof”运算符的用途是什么?举个例子。

答案:TypeScript 中的“typeof”运算符用于在编译时获取值或变量的类型。当您想要根据变量的类型执行类型检查时,它非常有用。这是一个例子:

const name = 'John';
type NameType = typeof name; // Result: string
function printType(value: any): void {
  const type = typeof value;
  console.log(`The type of ${value} is ${type}.`);
}
printType(42); // Output: "The type of 42 is number."
printType(true); // Output: "The type of true is boolean."
printType('Hello'); // Output: "The type of Hello is string."

在此示例中,NameType 类型被推断为字符串,因为 name 变量具有字符串值。

延伸阅读:TypeScript官方手册——typeof类型运算符(https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-operator)

39.TypeScript 接口中的“索引签名”是什么?举个例子。

答案:TypeScript 接口中的索引签名允许您根据属性的名称定义属性的类型。它们用于定义具有动态属性名称的对象。这是一个例子:

interface Dictionary {
  [key: string]: number;
}
const data: Dictionary = {
  apple: 1,
  banana: 2,
};
const value = data['banana'];
console.log(value); // Output: 2

在此示例中,Dictionary 接口允许您使用字符串键和数字值定义对象。

进一步阅读:TypeScript 官方手册 — 可索引类型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#indexable-types)

40.TypeScript 中的“类型谓词”是什么?举个例子。

答案:TypeScript 中的类型谓词用于缩小条件块中值的类型范围。它们提供了一种执行类型检查并获取更具体类型的方法。这是一个例子:

function isString(value: any): value is string {
  return typeof value === 'string';
}
function printLength(value: string | number): void {
  if (isString(value)) {
    console.log(`The length of the string is ${value.length}.`);
  } else {
    console.log(`The value is a number: ${value}`);
  }
}
printLength('Hello'); // Output: "The length of the string is 5."
printLength(42); // Output: "The value is a number: 42."

在此示例中,isString 函数是一个类型谓词,用于检查值是否为字符串。

外部链接:TypeScript 官方手册 — 用户定义的类型防护(https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)

总结

以上就是我今天这篇文章的全部内容,希望对你有所帮助,如果喜欢这篇文章的话,请记得关注我。

责任编辑:华轩 来源: web前端开发
相关推荐

2023-11-27 16:11:14

Web 开发HTML

2021-05-08 14:20:27

Redis面试数据库

2023-09-21 14:55:24

Web 开发TypeScript

2018-02-25 16:35:32

前端CSS面试题

2019-05-15 16:45:13

SpringBoot面试题Java

2023-09-26 22:19:36

Java限流器

2010-11-26 10:53:29

戴尔

2016-12-19 10:05:01

数据面试题PCA

2017-09-25 10:00:18

Hadoop面试题答案解析

2021-03-19 11:08:27

开发技能代码

2024-01-01 15:30:59

JavaScriptWeb 应用程序开发

2024-02-26 15:35:44

2024-04-15 08:34:43

2019-08-09 09:50:38

Java编程语言面试题

2022-02-11 14:01:22

底层String字符串

2020-11-13 16:00:57

SpringCloud面试架构

2021-10-26 11:45:22

Vue面试前端

2019-04-02 17:40:47

春招面试Python面试题

2010-08-30 16:42:57

谷歌面试题

2011-05-23 11:27:32

面试题面试java
点赞
收藏

51CTO技术栈公众号