LoginSignup
57
30

More than 1 year has passed since last update.

TypeScriptのStringとstringは何が違うのか

Last updated at Posted at 2019-10-28

はじめに

TypeScript では stringString は異なるものとして区別されます。この記事では、その違いについて説明します。

string

string は、 TypeScript において文字列を示す型です。以下のように文字列の値を持つ変数、パラメータなどに使用します。

let str: string = 'hello';

String

String は JavaScript におけるグローバルオブジェクトです。そのため、以下のように new を使用することで String のコンストラクタを呼び出すことが可能です。

let str: String = new String('hello');

両者の違い

上で述べたように、両者はそれぞれ別の型として扱われます。前者はプリミティブな文字列型、後者は String オブジェクトの型となります。これは、以下のようなコードを実行することでも確認することができます。

let str1: string = 'test';
let str2 = new String('test');

console.log(`str1: ${str1}`);                   // str1: test
console.log(`str2: ${str2}`);                   // str2: test
console.log(`typeof str1: ${typeof(str1)}`);    // typeof str1: string
console.log(`typeof str2: ${typeof(str2)}`);    // typeof str2: object
console.log(`str1 == str2: ${str1 == str2}`);   // str1 == str2: true
console.log(`str1 === str2: ${str1 === str2}`); // str1 === str2: false

また、プリミティブな文字列型である string の値を String 型の変数に格納することは可能ですが、その逆はできません。

let str1: String = 'hello'; // OK
let str2: string = new String('hello'); // Error

どちらを使うべきなのか

TypeScript の公式が述べているように、TypeScript ではstringのみを使用するべきとされています。これは String はプリミティブな型ではなく、ボックス化されたオブジェクトであり、ほとんど適切に使用されることがないためとされています。なので、特別な理由が無い限りTypeScriptでは string のみを使用すれば良いでしょう。

参考

57
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
57
30