首页 > 解决方案 > 如何在 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

标签: typescript

解决方案


所有打字稿类型在运行时都被删除,所以基本上没有办法在运行时知道它们。但是如果你想缩小条件块中的类型,那么你应该使用类型保护。你能做的最接近的事情是这样的:

type ORDER = 'WALK' | 'RUN'

function takeOrder(order: ORDER) {
    if (order === 'WALK' || order === 'RUN') console.log('ORDER')
}

我还建议您看一下这个SOF question。这和你问的很接近。


推荐阅读