【면접 필수사항】일반적인 TypeScript 면접 질문

PHPz
풀어 주다: 2024-09-11 06:41:40
원래의
416명이 탐색했습니다.

【Interview Essentials】ommon TypeScript Interview Questions

github: https://github.com/Jessie-jzn
웹사이트: https://www.jessieontheroad.com/

1. TypeScript를 사용하는 이유

1. 정적 유형 검사

TypeScript의 핵심 장점은 런타임이 아닌 컴파일 단계에서 일반적인 오류를 포착하는 데 도움이 되는 정적 유형 검사입니다. 이를 통해 코드 신뢰성과 안정성이 향상됩니다.

2. 향상된 코드 편집 경험

TypeScript의 유형 시스템을 사용하면 편집기에서 더 정확한 코드 완성, 리팩토링, 탐색 및 문서화 기능을 사용할 수 있어 개발 효율성이 크게 향상됩니다.

3. 코드 유지 관리성 향상

유형 선언을 사용하면 코드 의도와 구조를 더 쉽게 이해할 수 있으며 이는 팀 개발 환경에 특히 유용합니다.

4. 고급 언어 기능

TypeScript는 인터페이스, 열거형, 제네릭 등 JavaScript에는 없는 고급 기능을 지원하여 보다 구조화되고 확장 가능한 코드 개발을 촉진합니다.

5. 더 나은 도구 지원

TypeScript는 생성된 JavaScript 코드를 최적화하기 위한 다양한 컴파일러 옵션을 제공하고 TypeScript를 호환되는 JavaScript로 컴파일하여 다양한 JS 환경을 지원합니다.

2. TypeScript 대 JavaScript

일>
TypeScript JavaScript
Type System Static typing with compile-time type checks. Types can be specified for variables, function parameters, and return values. Dynamic typing with runtime type checks, which can lead to type-related runtime errors.
Type Annotations Supports type annotations to explicitly define types. E.g., let name: string = "Alice"; No type annotations. Types are determined at runtime.
Compilation Requires compilation to JavaScript. TypeScript compiler checks for type errors and generates equivalent JavaScript code. Runs directly in browsers or Node.js without a compilation step.
Object-Oriented Programming Richer OOP features such as classes, interfaces, abstract classes, and access modifiers. Basic OOP features with prototype-based inheritance.
Advanced Features Includes all ES6 and ES7 features, plus additional features like generics, enums, and decorators. Supports ES6 and later standards, but lacks some of the advanced features provided by TypeScript.
타입스크립트 자바스크립트 유형 시스템 컴파일 시간 유형 검사를 통한 정적 유형 지정. 변수, 함수 매개변수 및 반환 값에 대한 유형을 지정할 수 있습니다. 런타임 유형 검사를 통한 동적 유형 지정으로 유형 관련 런타임 오류가 발생할 수 있습니다. 유형 주석 유형을 명시적으로 정의하기 위한 유형 주석을 지원합니다. 예를 들어, 이름을 지정하십시오: string = "Alice"; 유형 주석이 없습니다. 유형은 런타임에 결정됩니다. 편집 JavaScript로 컴파일해야 합니다. TypeScript 컴파일러는 유형 오류를 확인하고 동등한 JavaScript 코드를 생성합니다. 컴파일 단계 없이 브라우저나 Node.js에서 직접 실행됩니다. 객체 지향 프로그래밍 클래스, 인터페이스, 추상 클래스, 액세스 한정자와 같은 더욱 풍부한 OOP 기능. 프로토타입 기반 상속이 포함된 기본 OOP 기능 고급 기능 모든 ES6 및 ES7 기능과 함께 제네릭, 열거형, 데코레이터와 같은 추가 기능이 포함됩니다. ES6 이상 표준을 지원하지만 TypeScript에서 제공하는 일부 고급 기능이 부족합니다.

3. TypeScript 中的基本数据类型

  • 布尔值:代表真值或假值。
  • 数字:表示整数和浮点数。
  • String:表示文本数据,使用单引号或双引号。
  • Array:表示指定类型的值的集合,使用 type[] 或 Array.
  • 元组:表示具有固定数量且指定类型的元素的数组。
  • Enum:表示一组命名常量。
  • Any:代表任意类型的值。不提供类型检查。
  • Void:表示没有值,常用作不返回值的函数的返回类型。
  • Null 和 Undefined:分别表示没有值和未初始化状态。
  • Never:表示永远不会发生的值,例如抛出错误或无限期运行的函数。
  • 对象:代表非原始类型。

4. TypeScript 中的泛型是什么?它们如何使用?

泛型允许函数、类和接口与任何类型一起使用,同时仍然强制执行类型安全。

示例:

function identity<T>(arg: T): T {
  return arg;
}

const numberIdentity = identity<number>(42);
const stringIdentity = identity<string>("Hello");

로그인 후 복사

在此示例中,恒等函数使用通用 ,允许它接受和返回任何类型的值。

5. TypeScript中unknown和any的区别

  • any Type:表示任意类型的值并绕过所有类型检查。它可以被赋予任何值,无需类型检查。
  • unknown Type:代表未知类型。未知类型的值在使用之前必须进行检查,这提供了一种更安全的方法来处理类型不确定的值。
let anyVar: any;
let unknownVar: unknown;

anyVar = 5;
anyVar.toUpperCase(); // No compile-time error, but might cause runtime error

unknownVar = "Hello";
if (typeof unknownVar === "string") {
  unknownVar.toUpperCase(); // Type check ensures safety
}

로그인 후 복사

6. readonly 修饰符和 const 关键字的区别

  • readonly 修饰符:用于对象属性,使其在初始化后不可变。
  • const 关键字:用于声明具有不可变引用的变量。对象的属性仍然可以修改。
const obj = { name: "John" };
obj.name = "Doe"; // Allowed

interface User {
  readonly id: number;
  name: string;
}

const user: User = { id: 1, name: "John" };
user.name = "Doe"; // Allowed
user.id = 2; // Error, `id` is readonly

로그인 후 복사

7. TypeScript 中的装饰器

装饰器是一种特殊的 TypeScript 功能,允许添加元数据或修改类、方法、属性或参数。

类型:

  • 类装饰器:应用于类构造函数以修改类行为或添加元数据。
  • 方法装饰器:应用于方法以更改其行为或添加元数据。
  • 访问器装饰器:用于获取或设置访问器以修改其行为。
  • 属性装饰器:应用于类属性以添加元数据或修改其行为。
  • 参数装饰器:应用于方法参数以添加元数据。

示例:

  • 类装饰器:
function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
  }

  greet() {
    return `Hello, ${this.greeting}`;
  }
}

로그인 후 복사
  • 方法装饰器:
function logMethod(target: any, propertyName: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`Method ${propertyName} called with args: ${JSON.stringify(args)}`);
    return originalMethod.apply(this, args);
  };
}

class Calculator {
  @logMethod
  add(a: number, b: number): number {
    return a + b;
  }
}

로그인 후 복사

用法:

通过在 tsconfig.json 中将experimentalDecorators 设置为 true 来启用装饰器。

8. 接口和类型的区别

interfacetype 都是用来定义对象类型的,但是它们有一些区别:

interface type
Basic Usage Defines the shape of objects, including properties and methods. Defines primitive types, object types, union types, intersection types, etc.
Extension Supports declaration merging. Multiple declarations of the same interface are automatically merged. Does not support declaration merging.
Union and Intersection Types Not supported. Supports union (`
Primitive Type Aliases Not supported. Supports aliasing primitive types.
Mapped Types Not supported. Supports mapped types.
Class Implementation Supports class implementation using implements. Does not support direct class implementation.
界面

类型

标题> 基本用法 定义对象的形状,包括属性和方法。 定义基本类型、对象类型、联合类型、交集类型等 扩展 支持声明合并。同一接口的多个声明会自动合并。 不支持声明合并。 并集和交集类型 不支持。 支持联合(` 原始类型别名 不支持。 支持基本类型别名。 映射类型 不支持。 支持映射类型。 类实现 支持使用实现的类实现。 不支持直接类实现。 表> 这些问题和答案应该涵盖基本概念和实际用法,有助于为 TypeScript 面试做好准备。

위 내용은 【면접 필수사항】일반적인 TypeScript 면접 질문의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!