TypeScript中的typeof

在 JavaScript 中,typeof 是一个运算符,用于获取一个值的类型。它返回一个字符串,表示值的数据类型。typeof 主要用于检测基本数据类型,如number、string、boolean、undefined、object、function和es6新增symbol类型。

let x = 10;
console.log(typeof x); // 输出: "number"

let y = "Hello, JavaScript!";
console.log(typeof y); // 输出: "string"

let z = true;
console.log(typeof z); // 输出: "boolean"

let obj = { key: "value" };
console.log(typeof obj); // 输出: "object"

let func = function () { };
console.log(typeof func); // 输出: "function"

let mySymbol = Symbol();
console.log(typeof mySymbol); // 输出: "symbol"          

而在TypeScript中typeof的功能更加强大,不仅可以获取基本数据类型,还能获取对象属性的类型、函数的类型、以及实例的类型。

1: 获取基本类型的变量类型

let num = 42;
let numType: typeof num; // 类型是 number

let str = "Hello, TypeScript!";
let strType: typeof str; // 类型是 string

let bool = true;
let boolType: typeof bool; // 类型是 boolean

let undefinedValue = undefined;
let undefinedType: typeof undefinedValue; // 类型是 undefined

let nullValue = null;
let nullType: typeof nullValue; // 类型是 object

2: 获取对象的类型

typeof 在 TypeScript 中可以用于获取对象的类型,包括具有深层嵌套结构的对象。当你使用 typeof 对象时,它会递归地获取该对象的所有嵌套属性的类型。

const nestedObject = {
    name: "John",
    age: 30,
    address: {
        city: "New York",
        postalCode: "10001",
    },
};

type NestedObjectType = typeof nestedObject;
// NestedObjectType 的类型是
// { name: string; age: number; address: { city: string; postalCode: string; } }

//对象属性的类型
type NameType = typeof person["name"]; // string
type AgeType = typeof person["age"]; // number
type AddressType = typeof person["address"]; // { city: string; postalCode: string }

3: 获取函数的类型

function add(a: number, b: number): number {
  return a + b;
}

let addFunctionType: typeof add; // 类型是 (a: number, b: number) => number
posted @ 2024-03-12 18:19  雪旭  阅读(7)  评论(0编辑  收藏  举报