← 都来码 / Dolaima← 例程索引typescript/school/types_demo.ts 原文

typescript/school/types_demo.ts · 813 字节 · 下载原文

// TypeScript 类型特性示范 —— interface / enum / 可选参数 / 泛型声明
// TypeScript feature demo -- interface / enum / optional params / generic declaration
//
// 这个例程存在的理由:它是**前端能力**的判据 —— 这些语法能在 JS 后端擦干净,
// 程序就该跑出和纯 JS 版一样的输出。

interface Point {
    x: number;
    y: number;
}

enum Color { Red, Green, Blue }

function scale(p: Point, k: number): number {
    return (p.x + p.y) * k;
}

function describe(kind: Color): string {
    if (kind === Color.Red) { return "red"; }
    if (kind === Color.Green) { return "green"; }
    return "blue";
}

const origin: Point = { x: 3, y: 4 };
println_int(scale(origin, 2));
print_str(describe(Color.Green) + "\n");
print_str(describe(Color.Blue) + "\n");