Skip to content

type guard about const enum and string #31319

@bluelovers

Description

@bluelovers

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:

Code

/**
 * Created by user on 2019/5/9.
 */

export const enum EnumTypeNode
{
	Pattern = "Pattern",
	Disjunction = "Disjunction",
}

export type NodeA = Disjunction | Pattern;

export interface NodeBase
{
	type: NodeA["type"]
}

export interface Disjunction extends NodeBase {
	type: EnumTypeNode.Disjunction
	alternatives: string[]
}

export interface Pattern extends NodeBase {
	type: EnumTypeNode.Pattern
	elements: string[]
}

let n: NodeA

if (n.type === "Disjunction")
{
	n.alternatives.slice()
}
else
{
	n.elements.slice()
	// Error: TS2339: Property 'elements' does not exist on type 'NodeA'.  Property 'elements' does not exist on type 'Disjunction'.
}

if (n.type === EnumTypeNode.Disjunction)
{
	n.alternatives.slice()
}
else
{
	n.elements.slice()
	// didn't have error
}

Expected behavior:

no error, if (n.type === "Disjunction") everything same as use if (n.type === EnumTypeNode.Disjunction)

Actual behavior:

Error: TS2339: Property 'elements' does not exist on type 'NodeA'.
Property 'elements' does not exist on type 'Disjunction'.

if (n.type === "Disjunction")
{
	n.alternatives.slice()
}
else
{
	n.elements.slice()
	// Error: TS2339: Property 'elements' does not exist on type 'NodeA'.
  Property 'elements' does not exist on type 'Disjunction'.
}

Playground Link:

Related Issues:

#14210

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: Literal TypesUnit types including string literal types, numeric literal types, Boolean literals, null, undefined

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions