示例工程 04-object-types-structural

04-object-types-structural/04-interface-vs-type/src/main.ts

typescript · 0.8 KB

运行:04 · interface-vs-type

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// 演示:interface 可声明合并,type 别名不能;readonly 是浅层只读
export interface Config {
  host: string;
}
 
export interface Config {
  port: number;
}
 
export type Point = {
  x: number;
  y: number;
};
 
export interface ReadonlyConfig {
  readonly id: number;
  label?: string;
}
 
export function describe(config: Config): string {
  return `${config.host}:${config.port}`;
}
 
export function relabel(config: ReadonlyConfig, label: string): ReadonlyConfig {
  return { ...config, label };
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const point: Point = { x: 1, y: 2 };
  const lines = [
    describe({ host: 'localhost', port: 8080 }),
    `${point.x},${point.y}`,
    relabel({ id: 1 }, 'demo').label ?? '(none)',
  ];
  for (const line of lines) {
    log(line);
  }
  return lines;
}