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

What is the difference between types String and string in TypeScript?

Câu trả lời

In TypeScript, the distinction between String and string is fundamental and revolves around the difference between object types and primitive types. Here's a detailed explanation:

Primitive Type: string

  • Definition: The string type (with a lowercase 's') in TypeScript represents the primitive data type for text data. It is used to denote string values that are immutable and do not possess properties or methods of their own. However, JavaScript provides wrapper objects that allow primitive strings to access methods.

  • Usage: The string type is extensively used in TypeScript for declaring variables, parameters, and return types when working with text data. It is the recommended way to handle strings in TypeScript due to its simplicity and performance benefits.

  • Characteristics:

    • It is a primitive type.
    • Immutable and does not have properties or methods.
    • Created using string literals, e.g., let myString: string = "Hello, World!".
    • Checked using typeof operator, which returns 'string'.

Object Type: String

  • Definition: The String type (with an uppercase 'S') refers to the String object, a wrapper around the primitive string type provided by JavaScript. This object type is constructed using the new String() syntax and can hold properties and methods.

  • Usage: The usage of String objects in TypeScript is minimal and generally not recommended. This is because primitive strings (string) are more efficient and easier to work with in most programming scenarios.

  • Characteristics:

    • It is an object type.
    • Can hold properties and methods.
    • Created using the new String() constructor, e.g., `let myStringObject: ...
junior

junior

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

entry

How to call base class constructor from child class in TypeScript?

junior

What is the purpose of Nullish Coalescing operator?

middle

How TypeScript is optionally statically typed language?

Bình luận

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

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