字面量类型
type Greeting = "Hello"
let greeting: Greeting
greeting = "Hello" // OK
greeting = "Hi" // Error: Type '"Hi"' is not assignable to type '"Hello"'
keyof
www.typescriptlang.org/docs/handbo…
The keyof operator takes an object type and produces a string or numeric literal union of its keys. The following type P is the same type as type P = "x" | "y"
keyof 返回字面量类型的联合。
type Point = { x: number; y: number };
type P = keyof Point; // 'x' | 'y'
type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish; // number
type Mapish = { [k: string]: boolean };
type M = keyof Mapish; // string | number
keyof any
// Record 的完整定义是
type Record<K extends keyof any, T> = {
[P in K]: T;
};
不管什么类型,它的key总是string,number,symbol中的一种。 keyof any 即 string | number | symbol.
因此在Record的定义,[P in K]的意思是对象的key可以取 string,number,symbol.
typeof
www.typescriptlang.org/docs/handbo…
JavaScript already has a typeof operator you can use in an expression context
// Prints "string"
console.log(typeof "Hello world");
TypeScript adds a typeof operator you can use in a type context to refer to the type of a variable or property
typeof 返回一个变量和属性的ts类型。
let s = "hello";
let n: typeof s; // string
function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>; // {x: number; y: number}
keyof typeof
const bmw = { name: "BMW", power: "1000hp" }
type bnwType = typeof bnw // {name: string, power: string}
type CarLiteralType = keyof typeof bmw // "name" | "power"
在enum上使用 keyof typeof
在 Typescript 中,enum 在编译时被用作类型,用来实现常量的类型安全,但是它们在运行时被视为对象。这是因为,当 Typescript 代码被编译为 Javascript 时,它们会被转换为普通对象。
这里 ColorsEnum 在运行时作为一个对象存在,不是一个类型,所以,我们需要一起使用 keyof typeof 这两个操作符,像下面代码展示的一样。
enum ColorsEnum { white = '#ffffff', black = '#000000', }
type Colors = keyof typeof ColorsEnum; // "white" | "black"