ast

package
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 29, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package ast defines a source-independent representation of TypeScript syntax.

Nodes are concrete structs behind sealed interfaces (Node, Type, Expr, Stmt, Decl, Member), so a type switch over a category stays exhaustive. Every node also reports a Kind for cheap discrimination.

All fields are exported and every node is usable as a zero-valued composite literal:

&ast.UnionType{Types: []ast.Type{ast.String, ast.Null}}

Positions are optional. RawType, RawExpr, and RawStmt carry verbatim text for syntax this package does not model; they print faithfully but are opaque to traversal.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ChildSeq

func ChildSeq(n Node) iter.Seq[Node]

ChildSeq yields the direct children of n.

func Collect

func Collect[T Node](seq iter.Seq[T]) []T

Collect drains seq into a slice.

func Filter

func Filter[T Node](seq iter.Seq[T], pred func(T) bool) iter.Seq[T]

Filter yields the nodes of seq satisfying pred.

func Inspect

func Inspect(n Node, f func(Node) bool)

Inspect walks the tree in depth-first preorder, calling f for each node. Returning false skips that node's children.

func OfType

func OfType[T Node](root Node) iter.Seq[T]

OfType yields every node in the tree with dynamic type T.

func Postorder

func Postorder(root Node) iter.Seq[Node]

Postorder yields every node depth first, children before parents. This is the order for bottom-up rewriting.

func Preorder

func Preorder(root Node) iter.Seq[Node]

Preorder yields every node depth first, parents before children.

func Walk

func Walk(v Visitor, n Node)

Walk traverses the tree rooted at n, driving v.

func WithParent

func WithParent(root Node) iter.Seq2[Node, Node]

WithParent yields each node with its parent; the root has a nil parent.

Types

type ArrayLit

type ArrayLit struct {
	Elems []Expr
	// contains filtered or unexported fields
}

ArrayLit is [a, b, c].

func (*ArrayLit) Kind

func (*ArrayLit) Kind() Kind

type ArrayType

type ArrayType struct {
	Elem Type
	// contains filtered or unexported fields
}

ArrayType is T[]. Use TypeRef("Array", T) for the generic spelling.

func Array

func Array(elem Type) *ArrayType

Array returns elem[].

func (*ArrayType) Kind

func (*ArrayType) Kind() Kind

type ArrowFunc

type ArrowFunc struct {
	Signature
	Body  *BlockStmt
	Expr  Expr
	Async bool
	// contains filtered or unexported fields
}

ArrowFunc is (a: A): R => body. Exactly one of Body and Expr is non-nil.

func (*ArrowFunc) Kind

func (*ArrowFunc) Kind() Kind

type AsExpr

type AsExpr struct {
	Expr  Expr
	Type  Type
	Const bool
	// contains filtered or unexported fields
}

AsExpr is x as T, or x as const when Const is set.

func (*AsExpr) Kind

func (*AsExpr) Kind() Kind

type Base

type Base struct {
	Loc token.Span
}

Base is embedded by every node and supplies position storage. The Loc field is promoted, so a parser can set it without knowing the node type.

func (*Base) SetSpan

func (b *Base) SetSpan(s token.Span)

func (*Base) Span

func (b *Base) Span() token.Span

type BigIntLit

type BigIntLit struct {
	Text string
	// contains filtered or unexported fields
}

BigIntLit is a bigint literal expression, stored in source form including the trailing n.

func (*BigIntLit) Kind

func (*BigIntLit) Kind() Kind

type BinaryExpr

type BinaryExpr struct {
	Op    string
	Left  Expr
	Right Expr
	// contains filtered or unexported fields
}

BinaryExpr is a binary or assignment operator application. The printer parenthesizes operands by precedence.

func (*BinaryExpr) Kind

func (*BinaryExpr) Kind() Kind

type Binding

type Binding struct {
	Base
	Name     PropertyName
	Type     Type
	Value    Expr
	Definite bool
}

Binding is a single name in a variable declaration.

func (*Binding) Kind

func (*Binding) Kind() Kind

type BlockStmt

type BlockStmt struct {
	Stmts []Stmt
	// contains filtered or unexported fields
}

BlockStmt is a braced statement list.

func (*BlockStmt) Kind

func (*BlockStmt) Kind() Kind

type BoolLit

type BoolLit struct {
	Value bool
	// contains filtered or unexported fields
}

BoolLit is true or false.

func Bool

func Bool(v bool) *BoolLit

Bool returns a boolean literal expression.

func (*BoolLit) Kind

func (*BoolLit) Kind() Kind

type CallExpr

type CallExpr struct {
	Callee   Expr
	Args     []Expr
	TypeArgs []Type
	Optional bool // fn?.(a)
	// contains filtered or unexported fields
}

CallExpr is fn<T>(a, b), optionally optional-chained.

func Call

func Call(callee Expr, args ...Expr) *CallExpr

Call returns a call expression.

func (*CallExpr) Kind

func (*CallExpr) Kind() Kind

type CallSignature

type CallSignature struct {
	Signature
	Docs *Doc
	// contains filtered or unexported fields
}

CallSignature is a bare call signature in an object type: <T>(a: A): R.

func (*CallSignature) Kind

func (*CallSignature) Kind() Kind

type ClassDecl

type ClassDecl struct {
	Name       *Ident // may be nil for a default-exported anonymous class
	TypeParams []*TypeParam
	Extends    *Heritage
	Implements []*Heritage
	Members    []Member
	Mods       Modifier
	Docs       *Doc
	// contains filtered or unexported fields
}

ClassDecl is a class declaration.

func (*ClassDecl) Kind

func (*ClassDecl) Kind() Kind

type ComputedName

type ComputedName struct {
	Base
	Expr Expr
}

ComputedName is a computed property name, [expr].

func (*ComputedName) Kind

func (*ComputedName) Kind() Kind

type CondExpr

type CondExpr struct {
	Cond Expr
	Then Expr
	Else Expr
	// contains filtered or unexported fields
}

CondExpr is cond ? then : else.

func (*CondExpr) Kind

func (*CondExpr) Kind() Kind

type ConditionalType

type ConditionalType struct {
	Check   Type
	Extends Type
	True    Type
	False   Type
	// contains filtered or unexported fields
}

ConditionalType is Check extends Extends ? True : False.

func (*ConditionalType) Kind

func (*ConditionalType) Kind() Kind

type ConstructSignature

type ConstructSignature struct {
	Signature
	Docs *Doc
	// contains filtered or unexported fields
}

ConstructSignature is new <T>(a: A): R.

func (*ConstructSignature) Kind

func (*ConstructSignature) Kind() Kind

type ConstructorType

type ConstructorType struct {
	Signature
	Abstract bool
	// contains filtered or unexported fields
}

ConstructorType is new (a: A) => R, optionally abstract.

func (*ConstructorType) Kind

func (*ConstructorType) Kind() Kind

type Decl

type Decl interface {
	Stmt
	// contains filtered or unexported methods
}

Decl is a statement that introduces a name. Every Decl is a Stmt.

type Doc

type Doc struct {
	Text []string
	Tags []DocTag
}

Doc is a JSDoc comment. Text holds the prose lines and Tags the block tags; an empty Doc prints nothing.

func Comment

func Comment(lines ...string) *Doc

Comment returns a Doc with the given prose lines.

func (*Doc) IsEmpty

func (d *Doc) IsEmpty() bool

IsEmpty reports whether the Doc would print nothing.

type DocTag

type DocTag struct {
	Name string
	Text string
}

DocTag is a JSDoc block tag, for example {Name: "deprecated", Text: "use X"}.

type EntityName

type EntityName interface {
	Node
	// contains filtered or unexported methods
}

EntityName is a dotted name usable in type position: A, A.B, A.B.C.

type EnumDecl

type EnumDecl struct {
	Name    *Ident
	Members []*EnumMember
	Mods    Modifier
	Docs    *Doc
	// contains filtered or unexported fields
}

EnumDecl is an enum declaration. Set ModConst for a const enum.

func (*EnumDecl) Kind

func (*EnumDecl) Kind() Kind

type EnumMember

type EnumMember struct {
	Base
	Name  PropertyName
	Value Expr // may be nil for auto-numbering
	Docs  *Doc
}

EnumMember is one member of an enum.

func (*EnumMember) Kind

func (*EnumMember) Kind() Kind

type ExportAssign

type ExportAssign struct {
	Expr    Expr
	Default bool // true for export default, false for export =
	Docs    *Doc
	// contains filtered or unexported fields
}

ExportAssign is export = X or export default X.

func (*ExportAssign) Kind

func (*ExportAssign) Kind() Kind

type ExportDecl

type ExportDecl struct {
	Decl       Decl // export <decl>
	Named      []ImportSpec
	Star       bool   // export * from "m"
	StarAs     string // export * as ns from "m"
	Module     string
	TypeOnly   bool
	Attributes []ImportAttribute
	Docs       *Doc
	// contains filtered or unexported fields
}

ExportDecl is an export clause or re-export. A non-nil Decl exports that declaration; otherwise it is a clause, optionally re-exporting Module.

func (*ExportDecl) Kind

func (*ExportDecl) Kind() Kind

type Expr

type Expr interface {
	Node
	// contains filtered or unexported methods
}

Expr is the interface for value-level expressions.

type ExprStmt

type ExprStmt struct {
	Expr Expr
	// contains filtered or unexported fields
}

ExprStmt is an expression statement.

func (*ExprStmt) Kind

func (*ExprStmt) Kind() Kind

type FunctionDecl

type FunctionDecl struct {
	Name *Ident
	Signature
	Body      *BlockStmt // may be nil
	Mods      Modifier
	Generator bool
	Docs      *Doc
	// contains filtered or unexported fields
}

FunctionDecl is a function declaration. A nil Body prints as an ambient signature, as required in a .d.ts.

func (*FunctionDecl) Kind

func (*FunctionDecl) Kind() Kind

type FunctionType

type FunctionType struct {
	Signature
	Abstract bool // unused for function types; present for symmetry
	// contains filtered or unexported fields
}

FunctionType is (a: A) => R.

func (*FunctionType) Kind

func (*FunctionType) Kind() Kind

type GetAccessor

type GetAccessor struct {
	Name PropertyName
	Mods Modifier
	Signature
	Body *BlockStmt // nil in declarations
	Docs *Doc
	// contains filtered or unexported fields
}

GetAccessor is get name(): T.

func (*GetAccessor) Kind

func (*GetAccessor) Kind() Kind

type Heritage

type Heritage struct {
	Base
	Name EntityName
	Args []Type
}

Heritage is one entry of an extends or implements clause.

func Extends

func Extends(name string, args ...Type) *Heritage

Extends returns a heritage clause entry for the named type.

func (*Heritage) Kind

func (*Heritage) Kind() Kind

type Ident

type Ident struct {
	Base
	Text string
}

Ident is a bare identifier. In a property-name position the printer quotes Text automatically when it is not a valid identifier.

func NewIdent

func NewIdent(text string) *Ident

NewIdent returns an identifier node for text.

func (*Ident) Kind

func (*Ident) Kind() Kind

type ImportAttribute

type ImportAttribute struct {
	Key   string
	Value string
}

ImportAttribute is a single with { key: "value" } entry.

type ImportDecl

type ImportDecl struct {
	Default    string // default binding, if any
	Namespace  string // * as NS binding, if any
	Named      []ImportSpec
	Module     string
	TypeOnly   bool
	Attributes []ImportAttribute
	Docs       *Doc
	// contains filtered or unexported fields
}

ImportDecl is an import declaration. With only Module set it prints as a side-effect import.

func (*ImportDecl) Kind

func (*ImportDecl) Kind() Kind

type ImportSpec

type ImportSpec struct {
	Name     string
	Alias    string
	TypeOnly bool
}

ImportSpec is one named binding in an import or export clause. Name is the name in the other module; Alias, when set, is the local name.

type ImportType

type ImportType struct {
	Module     string
	Qualifier  EntityName // may be nil
	Args       []Type
	TypeOf     bool // typeof import("mod")
	Attributes []ImportAttribute
	// contains filtered or unexported fields
}

ImportType is import("mod").Name<Args>.

func (*ImportType) Kind

func (*ImportType) Kind() Kind

type IndexExpr

type IndexExpr struct {
	Object   Expr
	Index    Expr
	Optional bool
	// contains filtered or unexported fields
}

IndexExpr is obj[index] or obj?.[index].

func (*IndexExpr) Kind

func (*IndexExpr) Kind() Kind

type IndexSignature

type IndexSignature struct {
	KeyName  string
	KeyType  Type
	Type     Type
	Readonly bool
	Static   bool
	Docs     *Doc
	// contains filtered or unexported fields
}

IndexSignature is [key: K]: V.

func (*IndexSignature) Kind

func (*IndexSignature) Kind() Kind

type IndexedAccessType

type IndexedAccessType struct {
	Object Type
	Index  Type
	// contains filtered or unexported fields
}

IndexedAccessType is T[K].

func Index

func Index(obj, idx Type) *IndexedAccessType

Index returns obj[idx].

func (*IndexedAccessType) Kind

func (*IndexedAccessType) Kind() Kind

type InferType

type InferType struct {
	Param *TypeParam
	// contains filtered or unexported fields
}

InferType is infer T, optionally with an extends constraint.

func (*InferType) Kind

func (*InferType) Kind() Kind

type InterfaceDecl

type InterfaceDecl struct {
	Name       *Ident
	TypeParams []*TypeParam
	Extends    []*Heritage
	Members    []Member
	Mods       Modifier
	Docs       *Doc
	// contains filtered or unexported fields
}

InterfaceDecl is an interface declaration.

func (*InterfaceDecl) Kind

func (*InterfaceDecl) Kind() Kind

type IntersectionType

type IntersectionType struct {
	Types []Type
	// contains filtered or unexported fields
}

IntersectionType is A & B & C.

func (*IntersectionType) Kind

func (*IntersectionType) Kind() Kind

type KeywordKind

type KeywordKind uint8

KeywordKind enumerates the intrinsic type keywords.

const (
	KwAny KeywordKind = iota
	KwUnknown
	KwNever
	KwVoid
	KwUndefined
	KwNull
	KwString
	KwNumber
	KwBoolean
	KwBigInt
	KwSymbol
	KwObject
)

func (KeywordKind) String

func (k KeywordKind) String() string

type KeywordType

type KeywordType struct {
	Keyword KeywordKind
	// contains filtered or unexported fields
}

KeywordType is an intrinsic type such as string or never.

func (*KeywordType) Kind

func (*KeywordType) Kind() Kind

type Kind

type Kind uint16

Kind discriminates node types without a type switch.

const (
	KindInvalid Kind = iota

	// Types
	KindKeywordType
	KindLiteralType
	KindTypeRef
	KindArrayType
	KindTupleType
	KindUnionType
	KindIntersectionType
	KindFunctionType
	KindConstructorType
	KindTypeLiteral
	KindIndexedAccessType
	KindMappedType
	KindConditionalType
	KindInferType
	KindTypeOperator
	KindTypeQuery
	KindTemplateLiteralType
	KindParenType
	KindImportType
	KindPredicateType
	KindThisType
	KindRestType
	KindOptionalType
	KindNamedTupleMember
	KindRawType

	// Members
	KindPropertySignature
	KindMethodSignature
	KindIndexSignature
	KindCallSignature
	KindConstructSignature
	KindGetAccessor
	KindSetAccessor
	KindPropertyDecl
	KindMethodDecl

	// Names
	KindIdent
	KindQualifiedName
	KindComputedName

	// Expressions
	KindStringLit
	KindNumberLit
	KindBigIntLit
	KindBoolLit
	KindNullLit
	KindUndefinedLit
	KindArrayLit
	KindObjectLit
	KindCallExpr
	KindNewExpr
	KindMemberExpr
	KindIndexExpr
	KindArrowFunc
	KindAsExpr
	KindSatisfiesExpr
	KindNonNullExpr
	KindTemplateLit
	KindUnaryExpr
	KindBinaryExpr
	KindCondExpr
	KindSpreadExpr
	KindRawExpr

	// Declarations & statements
	KindInterfaceDecl
	KindTypeAliasDecl
	KindEnumDecl
	KindClassDecl
	KindFunctionDecl
	KindVarDecl
	KindModuleDecl
	KindImportDecl
	KindExportDecl
	KindExportAssign
	KindReturnStmt
	KindExprStmt
	KindBlockStmt
	KindRawStmt

	// Structural
	KindSourceFile
	KindTypeParam
	KindParam
	KindEnumMember
	KindHeritage
	KindBinding
)

type LiteralKind

type LiteralKind uint8

LiteralKind discriminates the payload of a LiteralType.

const (
	LitString LiteralKind = iota
	LitNumber
	LitBoolean
	LitBigInt
)

type LiteralType

type LiteralType struct {
	LitKind LiteralKind
	Value   string
	Negated bool // for numeric literals: -1
	// contains filtered or unexported fields
}

LiteralType is a literal in type position. Value holds the source form for numbers and the unquoted text for strings.

func BoolLiteral

func BoolLiteral(v bool) *LiteralType

BoolLiteral returns the literal type true or false.

func NumberLiteral

func NumberLiteral(v string) *LiteralType

NumberLiteral returns the literal type for a numeric value in source form.

func StringLiteral

func StringLiteral(v string) *LiteralType

StringLiteral returns the literal type for a string value.

func (*LiteralType) Kind

func (*LiteralType) Kind() Kind

type MappedModifier

type MappedModifier int8

MappedModifier expresses the +/- prefix on readonly and ? in mapped types.

const (
	MappedUnset  MappedModifier = 0
	MappedAdd    MappedModifier = 1
	MappedRemove MappedModifier = -1
)

type MappedType

type MappedType struct {
	Param       *TypeParam // Name and Constraint hold K and Keys
	As          Type       // key remapping clause; may be nil
	Type        Type       // may be nil for { [K in Keys] }
	ReadonlyMod MappedModifier
	OptionalMod MappedModifier
	// contains filtered or unexported fields
}

MappedType is { [K in Keys as As]?: T }.

func (*MappedType) Kind

func (*MappedType) Kind() Kind

type Member

type Member interface {
	Node
	// contains filtered or unexported methods
}

Member is a member of an interface body, object type literal, or class body.

type MemberExpr

type MemberExpr struct {
	Object   Expr
	Prop     *Ident
	Optional bool
	// contains filtered or unexported fields
}

MemberExpr is obj.prop or obj?.prop.

func Dot

func Dot(obj Expr, prop string) *MemberExpr

Dot returns obj.prop.

func (*MemberExpr) Kind

func (*MemberExpr) Kind() Kind

type MethodDecl

type MethodDecl struct {
	Name     PropertyName
	Mods     Modifier
	Optional bool
	Signature
	Body *BlockStmt // may be nil
	Docs *Doc
	// contains filtered or unexported fields
}

MethodDecl is a class method. A nil Body prints as a signature only.

func (*MethodDecl) Kind

func (*MethodDecl) Kind() Kind

type MethodSignature

type MethodSignature struct {
	Name     PropertyName
	Optional bool
	Signature
	Docs *Doc
	// contains filtered or unexported fields
}

MethodSignature is a method in an interface or object type: name?<T>(a: A): R.

func (*MethodSignature) Kind

func (*MethodSignature) Kind() Kind

type Modifier

type Modifier uint32

Modifier is a bit set of declaration modifiers. Combine with |.

const (
	ModExport Modifier = 1 << iota
	ModDeclare
	ModDefault
	ModAbstract
	ModStatic
	ModReadonly
	ModAsync
	ModPublic
	ModPrivate
	ModProtected
	ModConst
	ModOverride
	ModAccessor
)

func (Modifier) Has

func (mo Modifier) Has(m Modifier) bool

Has reports whether every bit in m is set.

func (Modifier) With

func (mo Modifier) With(m Modifier) Modifier

With returns mo with the bits in m set.

func (Modifier) Without

func (mo Modifier) Without(m Modifier) Modifier

Without returns mo with the bits in m cleared.

type ModuleDecl

type ModuleDecl struct {
	ModuleKind ModuleKind
	Name       string // dotted for namespaces, module specifier for ambient
	Body       []Stmt
	Mods       Modifier
	Docs       *Doc
	// contains filtered or unexported fields
}

ModuleDecl is a namespace, ambient module, or global augmentation block.

func (*ModuleDecl) Kind

func (*ModuleDecl) Kind() Kind

type ModuleKind

type ModuleKind uint8

ModuleKind discriminates the flavours of module and namespace declaration.

const (
	ModuleNamespace ModuleKind = iota // namespace X { }
	ModuleAmbient                     // declare module "x" { }
	ModuleGlobal                      // declare global { }
)

type NamedTupleMember

type NamedTupleMember struct {
	Name     *Ident
	Optional bool
	Rest     bool
	Type     Type
	// contains filtered or unexported fields
}

NamedTupleMember is a labelled tuple element: [x: number, y?: string].

func (*NamedTupleMember) Kind

func (*NamedTupleMember) Kind() Kind

type NewExpr

type NewExpr struct {
	Callee   Expr
	Args     []Expr
	TypeArgs []Type
	// contains filtered or unexported fields
}

NewExpr is new C<T>(a).

func (*NewExpr) Kind

func (*NewExpr) Kind() Kind

type Node

type Node interface {
	// Span reports the source range of the node, or token.NoSpan if the node
	// was synthesized.
	Span() token.Span
	// Kind reports the node's discriminant.
	Kind() Kind
	// contains filtered or unexported methods
}

Node is the interface implemented by every AST node. It is sealed.

func Children

func Children(n Node) []Node

Children returns the direct child nodes of n in source order, omitting nils. Nodes carrying verbatim text report no children.

func Find

func Find(n Node, pred func(Node) bool) Node

Find returns the first node in preorder for which pred is true, or nil.

type NonNullExpr

type NonNullExpr struct {
	Expr Expr
	// contains filtered or unexported fields
}

NonNullExpr is x!.

func (*NonNullExpr) Kind

func (*NonNullExpr) Kind() Kind

type NullLit

type NullLit struct {
	// contains filtered or unexported fields
}

NullLit is null.

func (*NullLit) Kind

func (*NullLit) Kind() Kind

type NumberLit

type NumberLit struct {
	Text string
	// contains filtered or unexported fields
}

NumberLit is a numeric literal expression, stored in source form.

func Num

func Num(text string) *NumberLit

Num returns a numeric literal expression from source text.

func (*NumberLit) Kind

func (*NumberLit) Kind() Kind

type ObjectLit

type ObjectLit struct {
	Props []ObjectProp
	// contains filtered or unexported fields
}

ObjectLit is { a: 1, ...rest }.

func (*ObjectLit) Kind

func (*ObjectLit) Kind() Kind

type ObjectProp

type ObjectProp struct {
	Name      PropertyName
	Value     Expr
	Shorthand bool
	Spread    bool
	Docs      *Doc
}

ObjectProp is one entry of an object literal. Shorthand prints just the name; Spread prints ...Value.

type OptionalType

type OptionalType struct {
	Elem Type
	// contains filtered or unexported fields
}

OptionalType is T? inside a tuple.

func (*OptionalType) Kind

func (*OptionalType) Kind() Kind

type Param

type Param struct {
	Base
	Name     PropertyName // usually *Ident; may be a binding pattern rendered via RawExpr
	Type     Type         // may be nil
	Optional bool
	Rest     bool
	Default  Expr     // may be nil
	Mods     Modifier // parameter properties on constructors
	Docs     *Doc
}

Param is a function, method, or constructor parameter.

func (*Param) Kind

func (*Param) Kind() Kind

type ParenType

type ParenType struct {
	Inner Type
	// contains filtered or unexported fields
}

ParenType is an explicit parenthesization. The printer adds parentheses where precedence requires them, so this is only needed to preserve redundant ones from parsed source.

func (*ParenType) Kind

func (*ParenType) Kind() Kind

type Positioner

type Positioner interface {
	Node
	SetSpan(token.Span)
}

Positioner is implemented by every node, allowing position rewriting without a type switch.

type PredicateType

type PredicateType struct {
	Asserts   bool
	ParamName *Ident
	Type      Type // nil for a bare asserts x
	// contains filtered or unexported fields
}

PredicateType is a type predicate in return position.

func (*PredicateType) Kind

func (*PredicateType) Kind() Kind

type PropertyDecl

type PropertyDecl struct {
	Name     PropertyName
	Mods     Modifier
	Optional bool
	Definite bool // name!: T
	Type     Type
	Value    Expr // may be nil
	Docs     *Doc
	// contains filtered or unexported fields
}

PropertyDecl is a class property, which unlike a PropertySignature may carry modifiers, an initializer, and a definite-assignment assertion.

func (*PropertyDecl) Kind

func (*PropertyDecl) Kind() Kind

type PropertyName

type PropertyName interface {
	Node
	// contains filtered or unexported methods
}

PropertyName is the name position of a member: an identifier, a string or numeric literal, or a computed name.

type PropertySignature

type PropertySignature struct {
	Name     PropertyName
	Optional bool
	Readonly bool
	Type     Type // may be nil, meaning implicit any
	Docs     *Doc
	// contains filtered or unexported fields
}

PropertySignature is a property in an interface or object type.

func Prop

func Prop(name string, t Type) *PropertySignature

Prop returns a property signature. The printer quotes the name if it is not a valid identifier.

func (*PropertySignature) Kind

func (*PropertySignature) Kind() Kind

type QualifiedName

type QualifiedName struct {
	Base
	Left  EntityName
	Right *Ident
}

QualifiedName is a dotted name, Left.Right.

func (*QualifiedName) Kind

func (*QualifiedName) Kind() Kind

type RawExpr

type RawExpr struct {
	Text string
	// contains filtered or unexported fields
}

RawExpr carries verbatim TypeScript text in expression position.

func (*RawExpr) Kind

func (*RawExpr) Kind() Kind

type RawStmt

type RawStmt struct {
	Text string
	// contains filtered or unexported fields
}

RawStmt carries verbatim TypeScript text in statement position.

func (*RawStmt) Kind

func (*RawStmt) Kind() Kind

type RawType

type RawType struct {
	Text string
	// contains filtered or unexported fields
}

RawType carries verbatim TypeScript text in type position, for syntax this package does not model. It is opaque to traversal.

func Raw

func Raw(text string) *RawType

Raw returns a RawType carrying text.

func (*RawType) Kind

func (*RawType) Kind() Kind

type RestType

type RestType struct {
	Elem Type
	// contains filtered or unexported fields
}

RestType is ...T inside a tuple or parameter list.

func (*RestType) Kind

func (*RestType) Kind() Kind

type ReturnStmt

type ReturnStmt struct {
	Value Expr // may be nil
	// contains filtered or unexported fields
}

ReturnStmt is a return statement.

func (*ReturnStmt) Kind

func (*ReturnStmt) Kind() Kind

type SatisfiesExpr

type SatisfiesExpr struct {
	Expr Expr
	Type Type
	// contains filtered or unexported fields
}

SatisfiesExpr is x satisfies T.

func (*SatisfiesExpr) Kind

func (*SatisfiesExpr) Kind() Kind

type ScriptKind

type ScriptKind uint8

ScriptKind describes how a source file should be parsed and printed.

const (
	ScriptTS ScriptKind = iota
	ScriptTSX
	ScriptDTS
	ScriptJS
	ScriptJSX
)

type SetAccessor

type SetAccessor struct {
	Name PropertyName
	Mods Modifier
	Signature
	Body *BlockStmt // nil in declarations
	Docs *Doc
	// contains filtered or unexported fields
}

SetAccessor is set name(v: T).

func (*SetAccessor) Kind

func (*SetAccessor) Kind() Kind

type Signature

type Signature struct {
	TypeParams []*TypeParam
	Params     []*Param
	Return     Type // may be nil
}

Signature is the shared shape of anything callable: type parameters, parameters, and an optional return type. It is embedded rather than interface-implemented so that callers can construct it directly.

type SourceFile

type SourceFile struct {
	Base
	Name       string
	ScriptKind ScriptKind
	Leading    []string
	Stmts      []Stmt
}

SourceFile is a whole module. Leading holds file-level comment lines, emitted before everything else.

func (*SourceFile) Add

func (f *SourceFile) Add(stmts ...Stmt) *SourceFile

Add appends statements to the file and returns it, allowing chaining.

func (*SourceFile) Kind

func (*SourceFile) Kind() Kind

type SpreadExpr

type SpreadExpr struct {
	Expr Expr
	// contains filtered or unexported fields
}

SpreadExpr is ...x in a call or array literal.

func (*SpreadExpr) Kind

func (*SpreadExpr) Kind() Kind

type Stmt

type Stmt interface {
	Node
	// contains filtered or unexported methods
}

Stmt is the interface for statements.

type StringLit

type StringLit struct {
	Value string
	// contains filtered or unexported fields
}

StringLit is a string literal expression. Value is the decoded value; the printer handles quoting and escaping.

func Str

func Str(v string) *StringLit

Str returns a string literal expression.

func (*StringLit) Kind

func (*StringLit) Kind() Kind

type TemplateLit

type TemplateLit struct {
	Tag    Expr
	Quasis []string
	Exprs  []Expr
	// contains filtered or unexported fields
}

TemplateLit is a template literal, where len(Quasis) == len(Exprs)+1. A non-nil Tag makes it a tagged template.

func (*TemplateLit) Kind

func (*TemplateLit) Kind() Kind

type TemplateLiteralType

type TemplateLiteralType struct {
	Quasis []string
	Types  []Type
	// contains filtered or unexported fields
}

TemplateLiteralType is `a${B}c`, where len(Quasis) == len(Types)+1.

func (*TemplateLiteralType) Kind

func (*TemplateLiteralType) Kind() Kind

type ThisType

type ThisType struct {
	// contains filtered or unexported fields
}

ThisType is the this type.

func (*ThisType) Kind

func (*ThisType) Kind() Kind

type TupleType

type TupleType struct {
	Elems []Type // may contain *OptionalType, *RestType, *NamedTupleMember
	// contains filtered or unexported fields
}

TupleType is [A, B?, ...C[]].

func (*TupleType) Kind

func (*TupleType) Kind() Kind

type Type

type Type interface {
	Node
	// contains filtered or unexported methods
}

Type is the interface for type-level syntax.

var (
	Any       Type = &KeywordType{Keyword: KwAny}
	Unknown   Type = &KeywordType{Keyword: KwUnknown}
	Never     Type = &KeywordType{Keyword: KwNever}
	Void      Type = &KeywordType{Keyword: KwVoid}
	Undefined Type = &KeywordType{Keyword: KwUndefined}
	Null      Type = &KeywordType{Keyword: KwNull}
	String    Type = &KeywordType{Keyword: KwString}
	Number    Type = &KeywordType{Keyword: KwNumber}
	Boolean   Type = &KeywordType{Keyword: KwBoolean}
	BigInt    Type = &KeywordType{Keyword: KwBigInt}
	Symbol    Type = &KeywordType{Keyword: KwSymbol}
	Object    Type = &KeywordType{Keyword: KwObject}
)

Keyword singletons, safe to share because they carry no position or mutable state. Construct a KeywordType directly if you need a position.

func Intersection

func Intersection(types ...Type) Type

Intersection returns the intersection of types, flattening nested ones. One member is returned unwrapped; none becomes unknown.

func Nullable

func Nullable(t Type) Type

Nullable returns t | null.

func Optional

func Optional(t Type) Type

Optional returns t | undefined.

func StringUnion

func StringUnion(values ...string) Type

StringUnion returns a union of string literal types.

func Union

func Union(types ...Type) Type

Union returns the union of types, flattening nested unions and removing duplicate keywords. One member is returned unwrapped; none becomes never.

type TypeAliasDecl

type TypeAliasDecl struct {
	Name       *Ident
	TypeParams []*TypeParam
	Type       Type
	Mods       Modifier
	Docs       *Doc
	// contains filtered or unexported fields
}

TypeAliasDecl is a type alias declaration.

func (*TypeAliasDecl) Kind

func (*TypeAliasDecl) Kind() Kind

type TypeLiteral

type TypeLiteral struct {
	Members []Member
	// contains filtered or unexported fields
}

TypeLiteral is an anonymous object type: { a: string; b?: number }.

func (*TypeLiteral) Kind

func (*TypeLiteral) Kind() Kind

type TypeOperator

type TypeOperator struct {
	Op   TypeOperatorKind
	Type Type
	// contains filtered or unexported fields
}

TypeOperator is keyof T, unique symbol, or readonly T[].

func KeyOf

func KeyOf(t Type) *TypeOperator

KeyOf returns keyof t.

func (*TypeOperator) Kind

func (*TypeOperator) Kind() Kind

type TypeOperatorKind

type TypeOperatorKind uint8

TypeOperatorKind enumerates prefix type operators.

const (
	OpKeyOf TypeOperatorKind = iota
	OpUnique
	OpReadonly
)

func (TypeOperatorKind) String

func (o TypeOperatorKind) String() string

type TypeParam

type TypeParam struct {
	Base
	Name       *Ident
	Constraint Type // may be nil
	Default    Type // may be nil
	Variance   Variance
	Const      bool
	Docs       *Doc
}

TypeParam is a generic type parameter declaration.

func (*TypeParam) Kind

func (*TypeParam) Kind() Kind

type TypeQuery

type TypeQuery struct {
	Name EntityName
	Args []Type
	// contains filtered or unexported fields
}

TypeQuery is typeof x, optionally with type arguments.

func (*TypeQuery) Kind

func (*TypeQuery) Kind() Kind

type TypeRef

type TypeRef struct {
	Name EntityName
	Args []Type
	// contains filtered or unexported fields
}

TypeRef is a reference to a named type, with optional type arguments: User, Array<T>, ns.Thing<A, B>.

func Partial

func Partial(t Type) *TypeRef

Partial returns Partial<t>.

func Promise

func Promise(t Type) *TypeRef

Promise returns Promise<t>.

func ReadonlyOf

func ReadonlyOf(t Type) *TypeRef

Readonly returns Readonly<t>.

func Record

func Record(k, v Type) *TypeRef

Record returns Record<k, v>.

func Ref

func Ref(name string, args ...Type) *TypeRef

Ref returns a reference to the named type, splitting a dotted name.

func (*TypeRef) Kind

func (*TypeRef) Kind() Kind

type UnaryExpr

type UnaryExpr struct {
	Op   string
	Expr Expr
	// contains filtered or unexported fields
}

UnaryExpr is a prefix operator application such as !x, -x, typeof x, await x.

func (*UnaryExpr) Kind

func (*UnaryExpr) Kind() Kind

type UndefinedLit

type UndefinedLit struct {
	// contains filtered or unexported fields
}

UndefinedLit is undefined.

func (*UndefinedLit) Kind

func (*UndefinedLit) Kind() Kind

type UnionType

type UnionType struct {
	Types []Type
	// contains filtered or unexported fields
}

UnionType is A | B | C.

func (*UnionType) Kind

func (*UnionType) Kind() Kind

type VarDecl

type VarDecl struct {
	VarKind  VarKind
	Bindings []*Binding
	Mods     Modifier
	Docs     *Doc
	// contains filtered or unexported fields
}

VarDecl is a variable declaration statement, possibly with several bindings.

func (*VarDecl) Kind

func (*VarDecl) Kind() Kind

type VarKind

type VarKind uint8

VarKind is the binding form of a variable declaration.

const (
	VarConst VarKind = iota
	VarLet
	VarVar
	VarUsing
	VarAwaitUsing
)

func (VarKind) String

func (v VarKind) String() string

type Variance

type Variance uint8

Variance is an explicit variance annotation on a type parameter.

const (
	VarianceNone Variance = iota
	VarianceIn
	VarianceOut
	VarianceInOut
)

type Visitor

type Visitor interface {
	Visit(Node) Visitor
}

Visitor is called for each node; a non-nil result visits that node's children, allowing a scoped visitor to take over.

type VisitorFunc

type VisitorFunc func(Node) bool

VisitorFunc adapts a function to the Visitor interface. The function is re-used for children when it returns true.

func (VisitorFunc) Visit

func (f VisitorFunc) Visit(n Node) Visitor

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL