interface Box<T> { value: T }
type Boxify<T> = {
}
// { a: Box<string>, b: Box<number> }
type A = Boxify<{ a: string, b: number }>;
// Array<Box<number>>
type B = Boxify<number[]>;
// [Box<string>, Box<number>]
type C = Boxify<[string, boolean]>;
// lib.d.ts
type Readonly<T> = {
readonly [K in keyof T]: T[K]
}
// 在 TypeScript 3.4 之前代码会如何执行
// { readonly a: string, readonly b: number }
type A = Readonly<{ a: string, b: number }>;
// number[]
type B = Readonly<number[]>;
// [string, boolean]
type C = Readonly<[string, boolean]>;
// 在 TypeScript 3.4 中代码会如何运行
// { readonly a: string, readonly b: number }
type A = Readonly<{ a: string, b: number }>;
// readonly number[]
type B = Readonly<number[]>;
// readonly [string, boolean]
type C = Readonly<[string, boolean]>;
type Writable<T> = {
-readonly [K in keyof T]: T[K]
}
// { a: string, b: number }
type A = Writable<{
readonly a: string;
readonly b: number
}>;
// number[]
type B = Writable<readonly number[]>;
// [string, boolean]
type C = Writable<readonly [string, boolean]>;
let err1: readonly Set<number>; // 错误!
let err2: readonly Array<boolean>; // 错误!
let okay: readonly boolean[]; // 有效
// Type '"hello"'
let x = "hello" as const;
// Type 'readonly [10, 20]'
let y = [10, 20] as const;
// Type '{ readonly text: "hello" }'
let z = { text: "hello" } as const;
// Type '"hello"'
let x = <const>"hello";
// Type 'readonly [10, 20]'
let y = <const>[10, 20];
// Type '{ readonly text: "hello" }'
let z = <const>{ text: "hello" };
// 不使用引用或声明的类型。
// 我们只需要一个 const 断言。
function getShapes() {
let result = [
{ kind: "circle", radius: 100, },
{ kind: "square", sideLength: 50, },
] as const;
return result;
}
for (const shape of getShapes()) {
// 完美细化
if (shape.kind === "circle") {
console.log("Circle radius", shape.radius);
}
else {
console.log("Square side length", shape.sideLength);
}
}