5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

typeof についてTypeScript独自の用法とJavaScriptと共通の用法を整理。

Last updated at Posted at 2021-04-11

typeof演算子は、型コンテキストでは型定義、その他の場所ではデータ型の種類の文字列を返す。
前者はTypeScript独自の用法、後者はJavaScriptと共通の用法。

型コンテキストでは

型コンテキスト(TypeScriptで型定義を書く箇所)では、typeofは対象の型定義を返す。

const hito = {
  name: 'Taro',
  age: 18
}

const syuto = 'Tokyo';

let kuni = 'nihon';

const jinkou = 1000;

let jinkou2 = 1000;

const hito3: typeof hito = {
  name: 'hide',
  age: 20
}
// const hito3: {
//   name: string;
//   age: number;
// }

const syuto2: typeof syuto = 'Tokyo';
// const syuto2: "Tokyo"

type s = typeof syuto;
// type s = "Tokyo"

const syuto3: s = 'Tokyo'
// const syuto3: "Tokyo"

const kuni2: typeof kuni = 'amarica'
// const kuni2: string

type k = typeof kuni;
// type k = string

const kuni3: k = 'amarica'
// const kuni3: string

const jinkou3: typeof jinkou = 1000;
// const jinkou3: 1000

const jinkou4: typeof jinkou2 = 1001;
// const jinkou4: number

その他の場所では

型コンテキスト以外の場所では、typeofは対象のデータ型の種類を文字列で返す。
返しうる文字列は"string", "number", "bigint", "boolean", "symbol", "undefined", "object", "function"

const hito = {
  name: 'Taro',
  age: 18
}

const syuto = 'Tokyo';

const hito2 = typeof hito;

console.log(typeof hito); // object
console.log(typeof syuto); // string
console.log(hito2); // object
console.log(typeof hito2); // string (文字列'object'の型の種類string)

if (typeof hito2 === 'string') {
  console.log("hito2 is 'string'")
}
// hito2 is 'string'
5
2
1

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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?