如何在运行时确定打字稿中联合类型的确切类型?

时间:2020-02-17 11:31:41

标签: typescript typescript-typings

在打字稿中,联合类型定义为 ParsedValue ,它由一些基本类型和接口 Template 组成。

在如下所示的一些解析代码之后,parsedValue的类型取决于类型。现在,我想基于parsedValue的确切类型(联合类型的子类型)进行操作。

但是,我发现 as 关键字不起作用,原因是 Template 是一个接口,而不是一个类实现。

任何解决此问题的方法吗?

type ParsedValue = string | number | boolean | Template | null

interface Visitor {
    visit(template: Template)
}

class BasicVisitor implements Visitor {
    visit(template: Template) {
    }
}

interface Template {
    accept(visitor: Visitor)
}

function parse(value: string, type: string): ParsedValue {
    if (type == 'template') {
        // return a template instance
    } else if (type === 'string') {
        // return some string
    } else {
        // return null
    }
}

class Field {
    type: string
    value: string
    parsedValue: ParsedValue

    constructor(json any) {
        this.value = json.value.toString()
        this.type = json.type.toString()
        this.parsedValue = parse(this.value, this.type)
    }
}

const field = new Field({
    type: 'template',
    value: 'some template string'
})

const visitor = new BasicVisitor()

if (field.parsedValue !== null && field.parsedValue as Template) {
    // how to bypass this type judgement
    field.parsedValue.accept(visitor)
}

1 个答案:

答案 0 :(得分:0)

您应该尝试使用用户定义的类型防护来进行运行时类型检查和类型声明:https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards