DAGDA SEARCH | Back to results | Support

CodeQL library for TypeScript — CodeQL

Source: https://codeql.github.com/docs/codeql-language-guides/codeql-library-for-typescript/

CodeQL library for TypeScript

When you’re analyzing a TypeScript program, you can make use of the large collection of classes in the CodeQL library for TypeScript.

Overview

Support for analyzing TypeScript code is bundled with the CodeQL libraries for JavaScript, so you can include the full TypeScript library by importing the javascript.qll module:

import javascript

CodeQL libraries for JavaScript covers most of this library, and is also relevant for TypeScript analysis. This document supplements the JavaScript documentation with the TypeScript-specific classes and predicates.

Syntax

Most syntax in TypeScript is represented in the same way as its JavaScript counterpart. For example, a+b is represented by an AddExpr; the same as it would be in JavaScript. On the other hand, x as number is represented by TypeAssertion, a class that is specific to TypeScript.

Type annotations

The TypeExpr class represents anything that is part of a type annotation.

Only type annotations that are explicit in the source code occur as a TypeExpr. Types inferred by the TypeScript compiler are Type entities; for details about this, see the section on static type information.

There are several ways to access type annotations, for example:

The TypeExpr class provides some convenient member predicates such as isString() and isVoid() to recognize commonly used types.

The subclasses that represent type annotations are:

There are some subclasses that may be part of a type annotation, but are not themselves types:

Function signatures

The Function class is a broad class that includes both concrete functions and function signatures.

Function signatures can take several forms:

We recommend that you use the predicate Function.hasBody() to distinguish concrete functions from signatures.

Type parameters

The TypeParameter class represents type parameters, and the TypeParameterized class represents entities that can declare type parameters. Classes, interfaces, type aliases, functions, and mapped type expressions are all TypeParameterized.

You can access type parameters using the following predicates:

You can access type arguments using the following predicates:

To select references to a given type parameter, use getLocalTypeName() (see Name binding below).

Examples

Select expressions that cast a value to a type parameter:

import javascript

from TypeParameter param, TypeAssertion assertion
where assertion.getTypeAnnotation() = param.getLocalTypeName().getAnAccess()
select assertion, "Cast to type parameter."

Classes and interfaces

The CodeQL class ClassOrInterface is a common supertype of classes and interfaces, and provides some TypeScript-specific member predicates:

Note that the superclass of a class is an expression, not a type annotation. If the superclass has type arguments, it will be an expression of kind ExpressionWithTypeArguments.

Also see the documentation for classes in the “CodeQL libraries for JavaScript.”

To select the type references to a class or an interface, use getTypeName().

Statements

The following are TypeScript-specific statements:

Expressions

The following are TypeScript-specific expressions:

Ambient declarations

Type annotations, interfaces, and type aliases are considered ambient AST nodes, as is anything with a declare modifier.

The predicate ASTNode.isAmbient() can be used to determine if an AST node is ambient.

Ambient nodes are mostly ignored by control flow and data flow analysis. The outermost part of an ambient declaration has a single no-op node in the control flow graph, and it has no internal control flow.

Static type information

Static type information and global name binding is available for projects with “full” TypeScript extraction enabled. This option is enabled by default when you create databases with the CodeQL CLI.

Basic usage

The Type class represents a static type, such as number or string. The type of an expression can be obtained with Expr.getType().

Types that refer to a specific named type can be recognized in various ways:

The hasQualifiedName and hasUnderlyingType predicates have two overloads:

Example

The following query can be used to find all toString calls on a Node.js Buffer object:

import javascript

from MethodCallExpr call
where call.getReceiver().getType().hasUnderlyingType("Buffer")
  and call.getMethodName() = "toString"
select call

Working with types

Type entities are not associated with a specific source location. For instance, there can be many uses of the number keyword, but there is only one number type.

Some important member predicates of Type are:

A Type entity always belongs to exactly one of the following subclasses:

Additionally, Type has the following subclasses which overlap partially with those above:

Canonical names and named types

CanonicalName is a CodeQL class representing a qualified name relative to a root scope, such as a module or the global scope. It typically represents an entity such as a type, namespace, variable, or function. TypeName and Namespace are subclasses of this class.

Canonical names can be recognized using the hasQualifiedName predicate:

For convenience, this predicate is also available on other classes, such as TypeReference and TypeofType, where it forwards to the underlying canonical name.

Function types

There is no CodeQL class for function types, as any type with a call or construct signature is usable as a function. The type CallSignatureType represents such a signature (with or without the new keyword).

Signatures can be obtained in several ways:

Some important member predicates of CallSignatureType are:

Note that a signature is not associated with a specific declaration site.

Call resolution

Additional type information is available for invocation expressions:

Note that these refer to the call target as determined by the type system. The actual call target may differ at runtime, for instance, if the target is a method that has been overridden in a subclass.

Inheritance and subtyping

The declared supertypes of a named type can be obtained using TypeName.getABaseTypeName().

This operates at the level of type names, hence the specific type arguments used in the inheritance chain are not available. However, these can often be deduced using Type.getProperty or Type.getMethod which both take inheritance into account.

This only accounts for types explicitly mentioned in the extends or implements clause of a type. There is no predicate that determines subtyping or assignability between types in general.

The following two predicates can be useful for recognising subtypes of a given type:

Example

The following query can be used to find all classes that are React components, along with the type of their props property, which generally coincides with its first type argument:

import javascript

from ClassDefinition cls, TypeName name
where name = cls.getTypeName()
  and name.getABaseTypeName+().hasQualifiedName("React.Component")
select cls, name.getType().getProperty("props")

Name binding

In TypeScript, names can refer to variables, types, and namespaces, or a combination of these.

These concepts are modeled as distinct entities: Variable, TypeName, and Namespace. For example, the class C below introduces both a variable and a type:

class C {}
let x = C; // refers to the variable C
let y: C;  // refers to the type C

The variable C and the type C are modeled as distinct entities. One is a Variable, the other is a TypeName.

TypeScript also allows you to import types and namespaces, and give them local names in different scopes. For example, the import below introduces a local type name B:

import {C as B} from "./foo"

The local name B is represented as a LocalTypeName named B, restricted to just the file containing the import. An import statement can also introduce a Variable and a LocalNamespaceName.

The following table shows the relevant classes for working with each kind of name. The classes are described in more detail below.

Kind

Local alias

Canonical name

Definition

Access

Value

Variable

VarAccess

Type

LocalTypeName

TypeName

TypeDefinition

TypeAccess

Namespace

LocalNamespaceName

Namespace

NamespaceDefinition

NamespaceAccess

Note: TypeName and Namespace are only populated if the database is generated using full TypeScript extraction. LocalTypeName and LocalNamespaceName are always populated.

Type names

A TypeName is a qualified name for a type and is not bound to a specific lexical scope. The TypeDefinition class represents an entity that defines a type, namely a class, interface, type alias, enum, or enum member. The relevant predicates for working with type names are:

A LocalTypeName behaves like a block-scoped variable, that is, it has an unqualified name and is restricted to a specific scope. The relevant predicates are:

Examples

Find references that omit type arguments to a generic type.

It is best to use TypeName to resolve through imports and qualified names:

import javascript

from TypeDefinition def, TypeAccess access
where access.getTypeName().getADefinition() = def
  and def.(TypeParameterized).hasTypeParameters()
  and not access.hasTypeArguments()
select access, "Type arguments are omitted"

Find imported names that are used as both a type and a value:

import javascript

from ImportSpecifier spec
where exists (LocalTypeAccess access | access.getLocalTypeName().getADeclaration() = spec.getLocal())
  and exists (VarAccess access | access.getVariable().getADeclaration() = spec.getLocal())
select spec, "Used as both variable and type"

Namespace names

Namespaces are represented by the classes Namespace and LocalNamespaceName. The NamespaceDefinition class represents a syntactic definition of a namespace, which includes ordinary namespace declarations as well as enum declarations.

Note that these classes deal exclusively with namespaces referenced from inside type annotations, not through expressions.

A Namespace is a qualified name for a namespace, and is not bound to a specific scope. The relevant predicates for working with namespaces are:

A LocalNamespaceName behaves like a block-scoped variable, that is, it has an unqualified name and is restricted to a specific scope. The relevant predicates are:

Further reading