简体   繁体   中英

Tagged unions and tagging using literal types

In TypeScript 2.0 there were introduced tagged unions. To use them we have to introduce a discriminant property in interface, for example:

interface Action {
    type: "ACTION"
}

However I'm not able to use string literal type as a discriminant:

let actionName: "ACTION"

interface Action {
    type: actionName <- error: cannot find name "actionName"
}

I'm wondering if it's a feature or a bug.

Your string literal definition is wrong. let defines variable, not a type. It should be:

type actionName = "ACTION"

interface Action {
    type: actionName;
}

The solution is to use the following notation:

const ACTION: "ACTION" = "ACTION"

interface Action {
    type: typeof ACTION
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM