在進行前端技術面試的時候,我們經常會遇到TypeScript 的一些面試題,因此,今天這篇文章,我整理匯總了40道關于TypeScript 的基礎知識的面試題。
今天這期內容,主要是對 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/)
答案:TypeScript 中的靜態類型可以在開發過程中指定變量、函數參數和返回值的數據類型。這有助于及早捕獲與類型相關的錯誤,從而提高代碼質量和可維護性。
好處是擁有更好的代碼文檔、增強的工具支持以及提高的開發人員生產力。
延伸閱讀:TypeScript 官方手冊——基本類型(https://www.typescriptlang.org/docs/handbook/basic-types.html)
答案: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)
答:TypeScript 提供了多種好處,包括靜態類型、更好的代碼分析和工具支持、改進的代碼可讀性、早期錯誤檢測、更輕松的代碼重構以及增強的代碼文檔。它還使開發人員能夠編寫更易于維護和擴展的應用程序。
延伸閱讀:TypeScript 官方網站 — 為什么選擇 TypeScript?(https://www.typescriptlang.org/docs/handbook/why-typescript.html)
答案:您可以使用 ? 在接口中定義可選屬性。屬性名稱后面的修飾符。可選屬性可能存在于實現該接口的對象中,也可能不存在。這是一個例子:
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)
答:聯合類型允許一個變量有多種類型。它通過使用 | 來表示類型之間的符號。這允許變量存儲任何指定類型的值。這是一個例子:
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)
答案:當無法自動推斷類型時,TypeScript 中的類型斷言允許您顯式告訴編譯器變量的類型。這是使用 <type> 或 as type 語法實現的。這是一個例子:
let length: any = '5';let numberLength: number = <number>length; // Using <type> syntaxlet stringLength: number = length as number; // Using "as type" syntax
延伸閱讀:TypeScript 官方手冊——類型斷言(https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions)
答案:您可以使用 ? 定義帶有可選參數和默認參數的函數。可選參數的修飾符以及為參數分配默認值。這是一個例子:
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)
答案:TypeScript 中的泛型允許您創建可與各種類型一起使用的可重用組件或函數。它們支持強類型,同時保持使用不同數據類型的靈活性。這是一個例子:
function identity<T>(arg: T): T { return arg;}const result1 = identity<number>(42); // Explicitly specifying the typeconst result2 = identity('hello'); // Inferring the type
延伸閱讀:TypeScript 官方手冊——泛型(https://www.typescriptlang.org/docs/handbook/generics.html)
答案: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)
答案:類型防護是 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)
答案: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)
答案: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)
答案: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)
答案: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 官方手冊——實用類型(
回答:“鍵重映射”和“值重映射”是 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)
答案: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)
答案: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)
答:條件映射類型將條件類型和映射類型結合起來,根據條件執行類型轉換。它們允許您根據現有類型的屬性創建動態類型。這是一個例子:
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)
答案:條件類型中的“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: truetype 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)
答案:TypeScript 中的“排除”實用程序類型允許您通過從聯合中排除某些類型來創建新類型。它有助于創建聯合類型的子集。這是一個例子:
type Color = 'red' | 'green' | 'blue';type PrimaryColors = Exclude<Color, 'green' | 'blue'>;const primary: PrimaryColors = 'red'; // Okayconst 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)
答案: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)
答案:條件類型中的“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)
答:“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)
答案: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)
答案:“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)
答案: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)
答案: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)
回答: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)
答案: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)
答:裝飾器是 TypeScript 的一項功能,允許您修改類、方法或屬性的行為。它們使用 @decoratorName 語法聲明并在運行時執行。這是一個簡單的類裝飾器的示例:
function MyClassDecorator<T extends { new (...args: any[]): {} }>(constructor: T) { return class extends constructor { newProperty = 'decorated property'; hello = 'overridden'; };}@MyClassDecoratorclass 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)
答: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)
答案:TypeScript 中的條件類型允許您根據條件執行類型轉換。它們使您能夠創建依賴于其他類型之間關系的動態類型。這是一個例子:
type IsString<T> = T extends string ? true : false;type CheckString = IsString<string>; // Result: truetype CheckNumber = IsString<number>; // Result: false
在此示例中,IsString 條件類型檢查提供的類型是否為字符串。
當您想要基于其他值的類型創建類型安全的映射或過濾器時,條件類型非常有用。
延伸閱讀:TypeScript 官方手冊——條件類型(https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)
答案: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)
答案: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)
答案:TypeScript 中的模塊擴充允許您在外部模塊中添加新聲明或擴展現有聲明。當您想要向第三方庫添加功能時,它非常有用。這是一個例子:
// Original module in a third-party library// external-library.d.tsdeclare module 'external-library' { export function greet(name: string): string;}// Augment the module// augmentations.d.tsdeclare module 'external-library' { export function goodbye(name: string): string;}// Usageimport { 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)
答案: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)
答案:TypeScript 中的“typeof”運算符用于在編譯時獲取值或變量的類型。當您想要根據變量的類型執行類型檢查時,它非常有用。這是一個例子:
const name = 'John';type NameType = typeof name; // Result: stringfunction 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)
答案: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)
以上就是我今天這篇文章的全部內容,希望對你有所幫助,如果喜歡這篇文章的話,請記得關注我。
本文鏈接:http://www.tebozhan.com/showinfo-26-18994-0.html40 道Typescript 面試題及其答案與代碼示例
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com