1.

TypeScript string型|プリミティブとStringオブジェクトの違い

編集
この記事の要点
  • string 型は TypeScript のプリミティブな文字列型。小文字で書く
  • 大文字始まりの String は JS のオブジェクトラッパー型で、原則使わない
  • シングル / ダブル / バッククオートすべて使えるが、慣習的にシングルテンプレートリテラル
  • リテラル型(type Color = "red" | "blue")で文字列の値そのものを型にできる
  • 型推論で let s = "hello"stringconst s = "hello" はリテラル型 "hello" になる

string 型とは

TypeScript の string 型は、文字列(テキスト)を表すプリミティブ型です。JavaScript のすべての文字列値(シングルクオート、ダブルクオート、バッククオート)を含みます。

基本構文

let color: string = "blue";
color = 'red';                 // OK: 別の文字列を代入
color = `green ${color}`;      // OK: テンプレートリテラル

// 型推論
let name = "Alice";            // string と推論される
const greeting = "hello";      // "hello" リテラル型と推論される

クオートの 3 種類

記法特徴
シングル '...'慣習的に推奨(ESLint の quotes ルールで強制可)
ダブル "..."JSON との親和性。プロジェクトによる
バッククオート `...`テンプレートリテラル。変数展開 ${...} と複数行に対応

テンプレートリテラル

const user = "Bob";
const age  = 30;

// 変数展開
const msg = `Hello, ${user}! You are ${age} years old.`;
// "Hello, Bob! You are 30 years old."

// 複数行
const html = `
  <div>
    <h1>${user}</h1>
    <p>${age}歳</p>
  </div>
`;

// 式も埋め込める
const calc = `1 + 2 = ${1 + 2}`;  // "1 + 2 = 3"

プリミティブ string と String オブジェクトの違い

項目string(小文字)String(大文字)
用途プリミティブ文字列型(推奨)String オブジェクトのインスタンス型
生成リテラル "hi"new String("hi")
比較"a" === "a" → truenew String("a") === new String("a") → false
typeof"string""object"
非推奨度標準原則使わない
// 良い
const s: string = "hello";

// 悪い(オブジェクトを生成する。typeof は "object")
const bad: String = new String("hello");

// TypeScript は両者の代入互換性を許すが、ESLint の no-new-wrappers ルールで警告

リテラル型と Union

TypeScript では文字列の値そのものを型として表現できます。これによりタイプセーフな enum 風の表現が可能です。

// リテラル型
type Color = "red" | "green" | "blue";

const c: Color = "red";        // OK
const x: Color = "yellow";     // 型エラー

// 関数の引数に
function setTheme(mode: "light" | "dark") {
  // ...
}

setTheme("light");   // OK
setTheme("auto");    // 型エラー

let / const での型推論の違い

let a = "hello";    // a: string(再代入されうるので幅広い型)
const b = "hello";  // b: "hello"(再代入されないのでリテラル型)

// const のリテラル型は使い分けで威力を発揮
function go(dir: "up" | "down") { /* ... */ }

const d = "up";     // d: "up"
go(d);              // OK

let d2 = "up";      // d2: string
go(d2);             // 型エラー: string is not assignable to "up" | "down"

よく使う文字列メソッド

メソッド用途
length文字数(UTF-16 単位)
toUpperCase() / toLowerCase()大文字 / 小文字化
includes(x)含むかどうか
startsWith(x) / endsWith(x)先頭 / 末尾の判定
indexOf(x)位置取得(-1 で未発見)
slice(s, e) / substring(s, e)部分文字列の取り出し
split(sep)分割して配列に
trim() / trimStart() / trimEnd()前後の空白除去
replace(p, r)置換
repeat(n)n 回繰り返し
padStart(n, c) / padEnd(n, c)桁揃え

Number / Boolean からの変換

// 数値 -> 文字列
const n = 42;
const s1 = n.toString();        // "42"
const s2 = String(n);           // "42"
const s3 = `${n}`;              // "42"(テンプレートリテラル)

// 文字列 -> 数値
const s = "42";
const n1 = Number(s);           // 42
const n2 = parseInt(s, 10);     // 42
const n3 = parseFloat("3.14");  // 3.14
const n4 = +s;                  // 42(短いが可読性に注意)

厳密な型を活かす TypeScript 特有のパターン

// Template Literal Type(TS 4.1+)
type Route = `/${string}`;
const ok: Route = "/users";       // OK
const ng: Route = "users";        // 型エラー

// キー名の組み合わせを型生成
type Direction = "top" | "bottom";
type Side = "left" | "right";
type Corner = `${Direction}-${Side}`;
// "top-left" | "top-right" | "bottom-left" | "bottom-right"

よくあるトラブル

症状原因と対処
新しい文字列を代入したのに変わらない文字列はイミュータブルs.replace(...) の戻り値を変数に代入
length と思った文字数が違う絵文字や合成文字は UTF-16 で 2 単位以上。[...s].lengthIntl.Segmenter を使う
any や Object 型から文字列メソッドが呼べない型を絞る(typeof x === "string")またはキャスト
JSON 比較で string と String が一致しないnew String を使わない。リテラルかつ === を使う

FAQ

Q: string と String、どちらを使うべき?
A: 常に小文字の string を使います。大文字 String は JS のラッパーオブジェクトの型で、TS では推奨されません(lint で警告)。

Q: シングルとダブル、どちらが良い?
A: 好みとプロジェクトのコーディング規約次第。Prettier の既定はダブル、Airbnb スタイルはシングル。混在しないことが重要。

Q: as const は何のため?
A: 配列やオブジェクトの値をリテラル型に固定するため。const x = ["a", "b"] as const;readonly ["a", "b"] になる。

関連

  • データ型一覧 — 親カテゴリ
  • number / boolean — 他のプリミティブ型
  • リテラル型 / Union 型
  • Template Literal Type
  • as const — リテラル型へ固定
編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. String(文字列)
  2. Number (数値: 整数/浮動小数点数)
  3. Boolean (真偽値: true/false)
  4. Any (全ての型を許容)
  5. Array(配列)
  6. Tuple (値のペア)

最近更新/作成されたページ