首页 > 解决方案 > 防止相同类型的打字稿转换

问题描述

在我的打字稿程序中,我有两个可以相互转换的坐标系。它们都是 x,y,但具有不同的比例。我想设置打字稿,如果我将错误的类型传递给函数,它会警告我。

type Vec2 = [number,number]; // the base type

interface TileC extends Vec2 {};  // the two types I would like to be exclusive
interface ChunkC extends Vec2 {}; // the two types I would like to be exclusive

// example functions

let chunkSize = 32;

function tileToChunk(t: TileC): ChunkC {
  const [x,y] = t;
  const c: Vec2 = [Math.floor(x/chunkSize), Math.floor(y/chunkSize)];
  return c;
}

function chunkToTile(c: ChunkC): TileC {
  const [cx,cy] = c;
  return [cx*chunkSize, cy*chunkSize];
}

我希望以下是一个错误

let chunkCoord: ChunkC = tileToChunk([7,14]);
let wantError = tileToChunk(chunkCoord);

就目前而言,这编译得很好。我错过了编译器选项吗?

标签: typescript

解决方案


您不会缺少编译器选项,这是设计使然。TypeScript 编译为 JavaScript,因此在运行时没有可用的静态类型信息。

TypeScript 使用结构类型:

TypeScript 结构类型系统的基本规则是,如果 y 至少具有与 x 相同的成员,则 x 与 y 兼容。

https://www.typescriptlang.org/docs/handbook/type-compatibility.html

好消息是您可以使用Discriminate Unions来实现您想要的行为,例如通过添加一个kind属性:

interface TileC {
    x: number;
    y: number;
    kind: "Tile"
}

interface ChunkC {
    x: number;
    y: number;
    kind: "Chunk"
}

interface VecC = TileC | ChunkC

推荐阅读