typescript - 如何在 typescript 中测试自定义类型,例如类型 ORDER = 'WALK' | '跑'?
问题描述
我想为 takeOrder('WALK') 而不是字符串获取 ORDER,typeof 不能用于此:
type ORDER = 'WALK' | 'RUN'
function takeOrder(order: ORDER) {
console.log (order);
console.log (typeof order);
}
takeOrder('WALK'); // doesn't give ORDER
takeOrder('SLEEP'); // string
解决方案
所有打字稿类型在运行时都被删除,所以基本上没有办法在运行时知道它们。但是如果你想缩小条件块中的类型,那么你应该使用类型保护。你能做的最接近的事情是这样的:
type ORDER = 'WALK' | 'RUN'
function takeOrder(order: ORDER) {
if (order === 'WALK' || order === 'RUN') console.log('ORDER')
}
我还建议您看一下这个SOF question。这和你问的很接近。
推荐阅读
- mysql - 验证日期 mySQL
- javascript - 打字稿功能类型推断
- tensorflow - 使用 `tf.data` 有效统计 TFRecords 中的示例数?
- python - Python 3 继承问题
- python - python minmax 仅使用递归
- javascript - 如何使用扩展运算符复制同一变量中的键值?
- ios - iCloud Cloudkit CKFetchWebAuthTokenOperation
- python - E00001:尝试从文件中提取文本时,vscode 中的语法无效
- scala - 无法编译从 mllib 扩展的库
- node.js - AWS 链接 Dynamo DB 和 S3 存储桶