typescript - 防止相同类型的打字稿转换
问题描述
在我的打字稿程序中,我有两个可以相互转换的坐标系。它们都是 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 编译为 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
推荐阅读
- r - 有没有办法检查 R 包中的每个函数只针对其自己的 roxygen2 注释块中的导入?
- scala - 如何一起使用 Circe Optics 和 Decode
- python - pox sdn mininet,计算 udp 数据包
- c++ - 我无法使用继承 setter 和 getter 返回 const char * 变量
- sql - 按没有在 SELECT 列表中的列对数据进行排序
- javascript - 猫鼬预(验证)不起作用
- php - PHP将变量推送到array1,然后在循环中将其推送到array2
- vba - 如何使用 VBA 递归解析电子邮件中的数据?
- react-native - React Native 中的撤回/删除推送通知
- javascript - 在html中打开仪表板主页时如何显示空视图?