Câu hỏi phỏng vấn Typescript
Câu hỏi

What are assertion functions?

Câu trả lời

Assertion functions in TypeScript are a powerful feature that allows developers to perform runtime checks on the types of variables and ensure that they conform to expected types. These functions are particularly useful when dealing with values of unknown or any type, often when interacting with dynamic content such as user inputs or third-party libraries.

An assertion function in TypeScript is defined by its ability to throw an error if a given condition is not met, thereby asserting a specific type condition within the code. Unlike regular type assertions in TypeScript, which only affect TypeScript's compile-time type checking, assertion functions produce actual JavaScript code that performs checks during runtime.

Key Characteristics of Assertion Functions

  1. Runtime Type Checking: Assertion functions validate types at runtime, which is crucial for catching type-related errors in scenarios where compile-time checks are insufficient.

  2. Enhancing Code Safety: By verifying types or conditions at runtime, assertion functions prevent the further execution of code that might lead to runtime errors, thus enhancing the reliability and robustness of the application.

  3. Type Narrowing: After a successful assertion, TypeScript narrows the type of the variable within the scope, based on the assertion. This means if an assertion function checks whether a variable is of a certain type, TypeScript will assume that type for the variable in the subsequent code.

Syntax and Usage

An assertion function typically has a return type annotated with the asserts keyword followed by a condition. For example, an assertion function to check if a variable is a string might look like this:

typescript Copy
function assertIsString(value: unknown): asserts value is string {
  if (typeof value !== "string") {
    throw new Error("Value is not a string!");
  }
}

In this example, if value is not a string, the function ...

junior

junior

Gợi ý câu hỏi phỏng vấn

senior

What is Mixin Constructor Type?

expert

Explain the difference between declare enum vs declare const enum

junior

Which object oriented terms are supported by TypeScript?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào