TypeScript typeof 操作符

2021-08-111626次阅读TypeScript

在TypeScript中typeof操作符可以用来获取一个变量或对象的类型。

interface Person {
  name: string;
  age: number;
}

const sem: Person = { name: "semlinker", age: 30 };
type Sem = typeof sem; // type Sem = Person

在上面代码中,我们通过typeof操作符获取sem变量的类型并赋值给Sem类型变量,之后我们就可以使用Sem类型:

const lolo: Sem  = { name: "lolo", age: 5 }

你也可以对嵌套对象执行相同的操作,也可以用来获取函数对象的类型,比如:

function toArray(x: number): Array<number> {
  return [x];
}

type Func = typeof toArray; // -> (x: number) => number[]


const 断言

TypeScript 3.4 引入了一种新的字面量构造方式,也称为const断言。当我们使用const断言构造新的字面量表达式时,我们可以向编程语言发出以下readonly信号。

let x = "hello" as const;
type X = typeof x; // type X = "hello"

let y = [10, 20] as const;
type Y = typeof y; // type Y = readonly [10, 20]

let z = { text: "hello" } as const;
type Z = typeof z; // let z: { readonly text: "hello"; }

数组字面量应用const断言后,它将变成readonly元组,之后我们还可以通过typeof操作符获取元组中元素值的联合类型,具体如下:

type Data = typeof y[number]; // type Data = 10 | 20

这同样适用于包含引用类型的数组,比如包含普通的对象的数组。这里我们也来举一个具体的例子:

const locales = [
  {
    locale: "zh-CN",
    language: "中文"
  },
  {
    locale: "en",
    language: "English"
  }
] as const;

// type Locale = "zh-CN" | "en"
type Locale = typeof locales[number]["locale"];

另外在使用const断言的时候,我们还需要注意以下两个注意事项:

const断言只适用于简单的字面量表达式

// A 'const' assertions can only be applied to references to enum members, 
// or string, number, boolean, array, or object literals.
let a = (Math.random() < 0.5 ? 0 : 1) as const; // error

let b = Math.random() < 0.5 ? 0 as const :
    1 as const;

const 上下文不会立即将表达式转换为完全不可变

let arr = [1, 2, 3, 4];

let foo = {
    name: "foo",
    contents: arr,
} as const;

foo.name = "bar";   // error!
foo.contents = [];  // error!

foo.contents.push(5); // ...works!

typeof和keyof操作符

在TypeScript中, typeof操作符可以用来获取一个变量或对象的类型。而keyof操作符可以用于获取某种类型的所有键,其返回类型是联合类型。

const COLORS = {
  red: 'red',
  blue: 'blue'
}

// 首先通过typeof操作符获取Colors变量的类型,然后通过keyof操作符获取该类型的所有键,
// 即字符串字面量联合类型 'red' | 'blue'
type Colors = keyof typeof COLORS 
let color: Colors;
color = 'red' // Ok
color = 'blue' // Ok

// Type '"yellow"' is not assignable to type '"red" | "blue"'.
color = 'yellow' // Error

 

上一篇: 去除video标签获得焦点的边框  下一篇: React配置@根目录  

TypeScript typeof 操作符相关文章