40 道Typescript 面試題及其答案與代碼示例
在進(jìn)行前端技術(shù)面試的時(shí)候,我們經(jīng)常會(huì)遇到TypeScript 的一些面試題,因此,今天這篇文章,我整理匯總了40道關(guān)于TypeScript 的基礎(chǔ)知識(shí)的面試題。
今天這期內(nèi)容,主要是對(duì) TypeScript 內(nèi)容的特定面試題,并提供詳細(xì)的參考答案、代碼示例以及相關(guān)的延伸閱讀內(nèi)容。
那么,我們現(xiàn)在就開始進(jìn)入今天的內(nèi)容吧。
1.什么是 TypeScript,它與 JavaScript 有何不同?提供 TypeScript 代碼示例。
答案:TypeScript 是 JavaScript 的超集,為該語言添加了靜態(tài)類型。它允許開發(fā)人員定義變量、函數(shù)參數(shù)和返回值的數(shù)據(jù)類型,這有助于在編譯時(shí)而不是運(yùn)行時(shí)捕獲錯(cuò)誤。這是一個(gè)例子:
function greet(name: string): string {
return `Hello, ${name}!`;
}
const message: string = greet('John');
console.log(message); // Output: "Hello, John!"
延伸閱讀:TypeScript 官方網(wǎng)站(https://www.typescriptlang.org/)
2.解釋 TypeScript 中靜態(tài)類型的概念及其好處。
答案:TypeScript 中的靜態(tài)類型可以在開發(fā)過程中指定變量、函數(shù)參數(shù)和返回值的數(shù)據(jù)類型。這有助于及早捕獲與類型相關(guān)的錯(cuò)誤,從而提高代碼質(zhì)量和可維護(hù)性。
好處是擁有更好的代碼文檔、增強(qiáng)的工具支持以及提高的開發(fā)人員生產(chǎn)力。
延伸閱讀:TypeScript 官方手冊(cè)——基本類型(https://www.typescriptlang.org/docs/handbook/basic-types.html)
3.TypeScript 中的接口是什么?舉個(gè)例子。
答案:TypeScript 中的接口定義了對(duì)象結(jié)構(gòu)的契約,指定其屬性和方法的名稱和類型。它們促進(jìn)強(qiáng)大的類型檢查并實(shí)現(xiàn)更好的代碼組織。這是一個(gè)例子:
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 官方手冊(cè)——接口(https://www.typescriptlang.org/docs/handbook/interfaces.html)
4.使用 TypeScript 相對(duì)于純 JavaScript 有什么好處?
答:TypeScript 提供了多種好處,包括靜態(tài)類型、更好的代碼分析和工具支持、改進(jìn)的代碼可讀性、早期錯(cuò)誤檢測(cè)、更輕松的代碼重構(gòu)以及增強(qiáng)的代碼文檔。它還使開發(fā)人員能夠編寫更易于維護(hù)和擴(kuò)展的應(yīng)用程序。
延伸閱讀:TypeScript 官方網(wǎng)站 — 為什么選擇 TypeScript?(https://www.typescriptlang.org/docs/handbook/why-typescript.html)
5.如何在 TypeScript 的接口中定義可選屬性?舉個(gè)例子。
答案:您可以使用 ? 在接口中定義可選屬性。屬性名稱后面的修飾符??蛇x屬性可能存在于實(shí)現(xiàn)該接口的對(duì)象中,也可能不存在。這是一個(gè)例子:
interface Person {
name: string;
age?: number;
}
const john: Person = { name: 'John' };
const jane: Person = { name: 'Jane', age: 25 };
延伸閱讀:TypeScript 官方手冊(cè)——接口(https://www.typescriptlang.org/docs/handbook/interfaces.html)
6.解釋 TypeScript 中聯(lián)合類型的概念并提供示例。
答:聯(lián)合類型允許一個(gè)變量有多種類型。它通過使用 | 來表示類型之間的符號(hào)。這允許變量存儲(chǔ)任何指定類型的值。這是一個(gè)例子:
function printId(id: number | string): void {
console.log(`ID: ${id}`);
}
printId(123); // Output: "ID: 123"
printId('abc'); // Output: "ID: abc"
延伸閱讀:TypeScript 官方手冊(cè)——聯(lián)合類型(https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html)
7.TypeScript 中的類型斷言是什么?舉個(gè)例子。
答案:當(dāng)無法自動(dòng)推斷類型時(shí),TypeScript 中的類型斷言允許您顯式告訴編譯器變量的類型。這是使用 <type> 或 as type 語法實(shí)現(xiàn)的。這是一個(gè)例子:
let length: any = '5';
let numberLength: number = <number>length; // Using <type> syntax
let stringLength: number = length as number; // Using "as type" syntax
延伸閱讀:TypeScript 官方手冊(cè)——類型斷言(https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions)
8.如何在 TypeScript 中定義具有可選參數(shù)和默認(rèn)參數(shù)的函數(shù)?舉個(gè)例子。
答案:您可以使用 ? 定義帶有可選參數(shù)和默認(rèn)參數(shù)的函數(shù)??蛇x參數(shù)的修飾符以及為參數(shù)分配默認(rèn)值。這是一個(gè)例子:
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 官方手冊(cè)——函數(shù)(https://www.typescriptlang.org/docs/handbook/functions.html)
9.TypeScript 中的泛型是什么?舉個(gè)例子。
答案:TypeScript 中的泛型允許您創(chuàng)建可與各種類型一起使用的可重用組件或函數(shù)。它們支持強(qiáng)類型,同時(shí)保持使用不同數(shù)據(jù)類型的靈活性。這是一個(gè)例子:
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 官方手冊(cè)——泛型(https://www.typescriptlang.org/docs/handbook/generics.html)
10.通過示例解釋 TypeScript 中的“keyof”關(guān)鍵字。
答案:TypeScript 中的“keyof”關(guān)鍵字是一個(gè)類型運(yùn)算符,它返回表示對(duì)象鍵的文字類型的聯(lián)合。它允許您對(duì)對(duì)象鍵執(zhí)行類型安全操作。這是一個(gè)例子:
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person; // "name" | "age"
延伸閱讀:TypeScript 官方手冊(cè)——索引類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types)
11. TypeScript 中的類型保護(hù)是什么?它們?nèi)绾喂ぷ??舉個(gè)例子。
答案:類型防護(hù)是 TypeScript 表達(dá)式,它在運(yùn)行時(shí)檢查變量的類型,并允許您根據(jù)類型執(zhí)行不同的操作。它們可以實(shí)現(xiàn)更好的類型推斷,并提供一種更有效地處理聯(lián)合類型的方法。
這是使用 typeof 和 instanceof 類型保護(hù)的示例:
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 官方手冊(cè) — Type Guards(https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards)
12.解釋 TypeScript 中條件類型的概念。舉個(gè)例子。
答案:TypeScript 中的條件類型允許您創(chuàng)建依賴于條件的類型。它們用于根據(jù)類型之間的關(guān)系執(zhí)行類型推斷。這是一個(gè)例子:
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 是推斷函數(shù)返回類型的條件類型。
延伸閱讀:TypeScript 官方手冊(cè)——條件類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)
13.TypeScript 中的映射類型是什么?舉個(gè)例子。
答案:TypeScript 中的映射類型允許您通過將屬性映射到新類型來基于現(xiàn)有類型創(chuàng)建新類型。它們使您能夠輕松修改現(xiàn)有類型或向現(xiàn)有類型添加屬性。這是一個(gè)例子:
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 是一個(gè)映射類型,它使 Person 的所有屬性都是可選的。
延伸閱讀:TypeScript 官方手冊(cè) — 映射類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types)
14.解釋 TypeScript 中的“部分”實(shí)用程序類型。舉個(gè)例子。
答案:TypeScript 中的“部分”實(shí)用程序類型用于使現(xiàn)有類型的所有屬性成為可選。它允許您從現(xiàn)有類型創(chuàng)建具有可選屬性的新類型。這是一個(gè)例子:
interface Person {
name: string;
age: number;
}
type PartialPerson = Partial<Person>;
const john: PartialPerson = { name: 'John' };
在此示例中,PartialPerson 是具有來自 Person 接口的可選屬性的類型。
延伸閱讀:TypeScript 官方手冊(cè)——實(shí)用類型(https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)
15.TypeScript 中的“只讀”實(shí)用程序類型是什么?它是如何工作的?舉個(gè)例子。
答案:TypeScript 中的“Readonly”實(shí)用程序類型用于使現(xiàn)有類型的所有屬性變?yōu)橹蛔x。它可以防止對(duì)象創(chuàng)建后修改其屬性。這是一個(gè)例子:
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 官方手冊(cè)——實(shí)用類型(
16.映射類型中的“鍵重新映射”和“值重新映射”是什么?為每個(gè)提供示例。
回答:“鍵重映射”和“值重映射”是 TypeScript 中映射類型的兩個(gè)特性。
“鍵重新映射”允許您使用 as 關(guān)鍵字更改現(xiàn)有類型的鍵。這是一個(gè)例子:
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_”。
“值重新映射”允許您使用條件類型更改現(xiàn)有類型的值。這是一個(gè)例子:
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 官方手冊(cè) — 映射類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types)
17.解釋 TypeScript 中的“Pick”實(shí)用程序類型。舉個(gè)例子。
答案:TypeScript 中的“Pick”實(shí)用程序類型允許您通過從現(xiàn)有類型中選擇特定屬性來創(chuàng)建新類型。它有助于創(chuàng)建現(xiàn)有類型的子集。這是一個(gè)例子:
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 官方手冊(cè)——實(shí)用類型(https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys)
18.TypeScript 中的“Omit”實(shí)用程序類型是什么?它是如何工作的?舉個(gè)例子。
答案:TypeScript 中的“Omit”實(shí)用程序類型允許您通過從現(xiàn)有類型中排除特定屬性來創(chuàng)建新類型。它有助于創(chuàng)建刪除了某些屬性的類型。這是一個(gè)例子:
interface Person {
name: string;
age: number;
city: string;
}
type PersonWithoutCity = Omit<Person, 'city'>;
const john: PersonWithoutCity = { name: 'John', age: 30 };
在此示例中,PersonWithoutCity 是一種從 Person 接口中排除“city”屬性的類型。
延伸閱讀:TypeScript 官方手冊(cè)——實(shí)用類型(https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)
19.TypeScript 中的“條件映射類型”是什么?舉個(gè)例子。
答:條件映射類型將條件類型和映射類型結(jié)合起來,根據(jù)條件執(zhí)行類型轉(zhuǎn)換。它們?cè)试S您根據(jù)現(xiàn)有類型的屬性創(chuàng)建動(dòng)態(tài)類型。這是一個(gè)例子:
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 是一個(gè)條件映射類型,它將 Person 的數(shù)字屬性轉(zhuǎn)換為字符串。
延伸閱讀:TypeScript 官方手冊(cè) — 映射類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)
20.條件類型中“keyof”和“in”關(guān)鍵字的用途是什么?舉個(gè)例子。
答案:條件類型中的“keyof”關(guān)鍵字用于獲取對(duì)象類型的鍵的并集。它允許您以類型安全的方式使用對(duì)象的鍵?!癷n”關(guān)鍵字檢查屬性鍵是否存在于從“keyof”獲得的鍵的并集中。這是一個(gè)例子:
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 是一個(gè)條件類型,用于檢查提供的鍵是否為“name”。
延伸閱讀:TypeScript 官方手冊(cè) — keyof Type Operator、TypeScript 官方手冊(cè) — in Operator(https://www.typescriptlang.org/docs/handbook/advanced-types.html#keyof-type-operator)
21.解釋 TypeScript 中的“排除”實(shí)用程序類型。舉個(gè)例子。
答案:TypeScript 中的“排除”實(shí)用程序類型允許您通過從聯(lián)合中排除某些類型來創(chuàng)建新類型。它有助于創(chuàng)建聯(lián)合類型的子集。這是一個(gè)例子:
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 是一種從顏色聯(lián)合中排除“綠色”和“藍(lán)色”顏色的類型。
延伸閱讀:TypeScript 官方手冊(cè)——實(shí)用類型(https://www.typescriptlang.org/docs/handbook/utility-types.html#excludetype-excludedunion)
22.TypeScript 中的“模板文字類型”是什么?舉個(gè)例子。
答案:TypeScript 中的模板文字類型允許您使用模板文字語法來操作類型中的字符串。它們提供了一種基于字符串模式創(chuàng)建復(fù)雜類型的方法。這是一個(gè)例子:
type Greeting<T extends string> = `Hello, ${T}!`;
type GreetJohn = Greeting<'John'>; // Result: "Hello, John!"
type GreetJane = Greeting<'Jane'>; // Result: "Hello, Jane!"
在此示例中,Greeting 是一個(gè)模板文字類型,它根據(jù)提供的名稱生成問候語。
延伸閱讀:TypeScript 官方手冊(cè)——模板文字類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#template-literal-types)
23.解釋條件類型中的“infer”關(guān)鍵字。舉個(gè)例子。
答案:條件類型中的“infer”關(guān)鍵字用于從條件類型中的另一種類型推斷出類型。它允許您捕獲類型并將其分配給類型變量。這是一個(gè)例子:
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 是一個(gè)條件類型,它使用“infer”關(guān)鍵字推斷函數(shù)的返回類型。
延伸閱讀:TypeScript 官方手冊(cè)——條件類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)
24.TypeScript 中的“keyof”和“typeof”關(guān)鍵字有何用途?為每個(gè)提供示例。
答:“keyof”關(guān)鍵字用于獲取對(duì)象類型的鍵的并集,“typeof”關(guān)鍵字用于獲取值的類型。以下是每個(gè)示例:
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 }
在第一個(gè)示例中,PersonKeys 是表示 Person 接口的鍵聯(lián)合的類型。在第二個(gè)示例中,JohnType 是表示 john 對(duì)象類型的類型。
延伸閱讀:TypeScript 官方手冊(cè) — keyof 類型運(yùn)算符、TypeScript 官方手冊(cè) — typeof 類型運(yùn)算符(https://www.typescriptlang.org/docs/handbook/advanced-types.html#keyof-type-operator)
25.TypeScript 中的“const 斷言”是什么?舉個(gè)例子。
答案:TypeScript 中的“Const 斷言”允許您通知編譯器特定的文字表達(dá)式應(yīng)被視為文字而不是擴(kuò)展類型。這是一個(gè)例子:
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 對(duì)象被視為具有只讀屬性的常量對(duì)象。
延伸閱讀:TypeScript官方手冊(cè)——文字類型加寬(https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions)
26.TypeScript 中的“私有”和“受保護(hù)”訪問修飾符是什么?為每個(gè)提供示例。
答案:“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 官方手冊(cè)——類(https://www.typescriptlang.org/docs/handbook/classes.html)
27.解釋 TypeScript 條件類型中的“keyof T extends K”構(gòu)造。舉個(gè)例子。
答案:TypeScript 條件類型中的“keyof T extends K”構(gòu)造用于使用“extends”關(guān)鍵字根據(jù)指定條件過濾對(duì)象類型的鍵。這是一個(gè)例子:
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;
// }
在此示例中,F(xiàn)ilterProperties 是一個(gè)條件映射類型,它根據(jù)值類型過濾 Person 的屬性。
延伸閱讀:TypeScript 官方手冊(cè)——條件類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)
28.TypeScript 中的“mixins”是什么?舉個(gè)例子。
答案:TypeScript 中的 Mixins 允許您通過將某個(gè)類與一個(gè)或多個(gè)其他類組合來向該類添加行為。它支持代碼重用和組合。這是一個(gè) 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 類充當(dāng) mixin,將 print 方法添加到 MyObject 類。
延伸閱讀:TypeScript 官方手冊(cè) — Mixins(https://www.typescriptlang.org/docs/handbook/mixins.html)
29.解釋 TypeScript 中“聲明合并”的概念。舉個(gè)例子。
回答:TypeScript 中的“聲明合并”是編譯器將同一實(shí)體的多個(gè)聲明合并到單個(gè)定義中的過程。它允許您擴(kuò)展接口、函數(shù)、類和枚舉。
interface Person {
name: string;
}
interface Person {
age: number;
}
const john: Person = { name: 'John', age: 30 };
console.log(john); // Output: { name: 'John', age: 30 }
在此示例中,編譯器將兩個(gè) Person 接口合并為一個(gè)定義,允許 john 同時(shí)具有 name 和age 屬性。
延伸閱讀:TypeScript官方手冊(cè)——聲明合并(https://www.typescriptlang.org/docs/handbook/declaration-merging.html)
30.TypeScript 中的“noUncheckedIndexedAccess”編譯器選項(xiàng)是什么?為什么它很有用?舉個(gè)例子。
答案:TypeScript 中的“noUncheckedIndexedAccess”編譯器選項(xiàng)用于在使用索引訪問屬性時(shí)捕獲潛在的未定義或空值。它通過避免運(yùn)行時(shí)錯(cuò)誤來幫助提高代碼安全性。
// tsconfig.json
{
"compilerOptions": {
"noUncheckedIndexedAccess": true
}
}
這是一個(gè)例子:
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”會(huì)引發(fā)錯(cuò)誤,因?yàn)?data[fruit] 可能未定義或?yàn)?null。
進(jìn)一步閱讀:TypeScript 編譯器選項(xiàng)(https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess)
31.TypeScript 中的“裝飾器”是什么?舉個(gè)例子。
答:裝飾器是 TypeScript 的一項(xiàng)功能,允許您修改類、方法或?qū)傩缘男袨?。它們使?@decoratorName 語法聲明并在運(yùn)行時(shí)執(zhí)行。這是一個(gè)簡(jiǎn)單的類裝飾器的示例:
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 函數(shù)是一個(gè)類裝飾器,用于修改 MyClass 類的行為。
延伸閱讀:TypeScript 官方手冊(cè)——裝飾器(https://www.typescriptlang.org/docs/handbook/decorators.html)
32.解釋 TypeScript 中的“abstract”關(guān)鍵字。舉個(gè)例子。
答:TypeScript 中的“abstract”關(guān)鍵字用于定義抽象類和方法。抽象類不能直接實(shí)例化;它們只能被延長(zhǎng)。抽象方法在抽象類中沒有實(shí)現(xiàn),必須在派生類中實(shí)現(xiàn)。這是一個(gè)例子:
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 類是一個(gè)具有抽象方法 area() 的抽象類。Circle 類擴(kuò)展了 Shape 類并實(shí)現(xiàn)了 area() 方法。
延伸閱讀:TypeScript官方手冊(cè)——抽象類(https://www.typescriptlang.org/docs/handbook/classes.html#abstract-classes)
33.什么是 TypeScript 中的“條件類型”,它們?yōu)槭裁从杏茫颗e個(gè)例子。
答案:TypeScript 中的條件類型允許您根據(jù)條件執(zhí)行類型轉(zhuǎn)換。它們使您能夠創(chuàng)建依賴于其他類型之間關(guān)系的動(dòng)態(tài)類型。這是一個(gè)例子:
type IsString<T> = T extends string ? true : false;
type CheckString = IsString<string>; // Result: true
type CheckNumber = IsString<number>; // Result: false
在此示例中,IsString 條件類型檢查提供的類型是否為字符串。
當(dāng)您想要基于其他值的類型創(chuàng)建類型安全的映射或過濾器時(shí),條件類型非常有用。
延伸閱讀:TypeScript 官方手冊(cè)——條件類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)
34.TypeScript 中屬性的“只讀”修飾符是什么?舉個(gè)例子。
答案:TypeScript 中的“readonly”修飾符用于使類或接口的屬性變?yōu)橹蛔x,這意味著它們的值一旦設(shè)置就無法更改。這是一個(gè)例子:
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 屬性被標(biāo)記為只讀。
延伸閱讀:TypeScript 官方手冊(cè)——類(https://www.typescriptlang.org/docs/handbook/classes.html#readonly-modifier)
35.解釋 TypeScript 中的“as const”斷言。舉個(gè)例子。
答案:TypeScript 中的“as const”斷言用于推斷數(shù)組和對(duì)象的文字類型。它告訴編譯器該值應(yīng)被視為常量,而不是擴(kuò)展到其基本類型。這是一個(gè)例子:
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 數(shù)組和 person 對(duì)象的類型分別被推斷為只讀元組和對(duì)象。
延伸閱讀:TypeScript 官方手冊(cè)——文字類型(https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions)
36.TypeScript 中的“模塊增強(qiáng)”是什么?舉個(gè)例子。
答案:TypeScript 中的模塊擴(kuò)充允許您在外部模塊中添加新聲明或擴(kuò)展現(xiàn)有聲明。當(dāng)您想要向第三方庫添加功能時(shí),它非常有用。這是一個(gè)例子:
// 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 函數(shù)來增強(qiáng)“external-library”模塊。
延伸閱讀:TypeScript 官方手冊(cè)——模塊增強(qiáng)(https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)
37.TypeScript 中的“keyof”運(yùn)算符有何用途?舉個(gè)例子。
答案:TypeScript 中的“keyof”運(yùn)算符用于獲取對(duì)象類型的鍵的并集。它允許您以類型安全的方式使用對(duì)象的鍵。這是一個(gè)例子:
interface Person {
name: string;
age: number;
}
type PersonKeys = keyof Person; // Result: "name" | "age"
在此示例中,PersonKeys 是表示 Person 接口的鍵的并集的類型。
延伸閱讀:TypeScript官方手冊(cè)——keyof類型運(yùn)算符(https://www.typescriptlang.org/docs/handbook/advanced-types.html#keyof-type-operator)
38.TypeScript 中“typeof”運(yùn)算符的用途是什么?舉個(gè)例子。
答案:TypeScript 中的“typeof”運(yùn)算符用于在編譯時(shí)獲取值或變量的類型。當(dāng)您想要根據(jù)變量的類型執(zhí)行類型檢查時(shí),它非常有用。這是一個(gè)例子:
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 類型被推斷為字符串,因?yàn)?name 變量具有字符串值。
延伸閱讀:TypeScript官方手冊(cè)——typeof類型運(yùn)算符(https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-operator)
39.TypeScript 接口中的“索引簽名”是什么?舉個(gè)例子。
答案:TypeScript 接口中的索引簽名允許您根據(jù)屬性的名稱定義屬性的類型。它們用于定義具有動(dòng)態(tài)屬性名稱的對(duì)象。這是一個(gè)例子:
interface Dictionary {
[key: string]: number;
}
const data: Dictionary = {
apple: 1,
banana: 2,
};
const value = data['banana'];
console.log(value); // Output: 2
在此示例中,Dictionary 接口允許您使用字符串鍵和數(shù)字值定義對(duì)象。
進(jìn)一步閱讀:TypeScript 官方手冊(cè) — 可索引類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#indexable-types)
40.TypeScript 中的“類型謂詞”是什么?舉個(gè)例子。
答案:TypeScript 中的類型謂詞用于縮小條件塊中值的類型范圍。它們提供了一種執(zhí)行類型檢查并獲取更具體類型的方法。這是一個(gè)例子:
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 函數(shù)是一個(gè)類型謂詞,用于檢查值是否為字符串。
外部鏈接:TypeScript 官方手冊(cè) — 用戶定義的類型防護(hù)(https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)
總結(jié)
以上就是我今天這篇文章的全部?jī)?nèi)容,希望對(duì)你有所幫助,如果喜歡這篇文章的話,請(qǐng)記得關(guān)注我。