示例工程 04-object-types-structural
04-object-types-structural/04-interface-vs-type/types.test-d.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = T;
import type { Config, Point, ReadonlyConfig } from './src/main.js';
// 两个 interface 声明合并成一个
type Case1 = Expect<Equal<keyof Config, 'host' | 'port'>>;
type Case2 = Expect<Equal<Config, { host: string; port: number }>>;
// 工具类型都是对键空间的映射
type Case3 = Expect<Equal<Partial<Point>, { x?: number; y?: number }>>;
type Case4 = Expect<Equal<Pick<Point, 'x'>, { x: number }>>;
type Case5 = Expect<Equal<Omit<Point, 'y'>, { x: number }>>;
// readonly 只约束赋值,不阻止创建新对象
const config: ReadonlyConfig = { id: 1 };
// @ts-expect-error: readonly 属性不可写
config.id = 2;
// exactOptionalPropertyTypes 下不能显式传 undefined
// @ts-expect-error: label 不能是 undefined
const explicit: ReadonlyConfig = { id: 2, label: undefined };
export { config, explicit };