How to use typescript

Comprehensive typescript code examples:

How to use typescript.tokenToString:

120
121
122
123
124
125
126
127
128
129
CurlyWalker.prototype.checkStatement = function (statement, node, childIndex, end) {
    if (end === void 0) { end = statement.end; }
    var sameLine = tsutils_1.isSameLine(this.sourceFile, statement.pos, statement.end);
    if (statement.kind !== ts.SyntaxKind.Block && !(this.options.ignoreSameLine && sameLine)) {
        var token = node.getChildAt(childIndex, this.sourceFile);
        var tokenText = ts.tokenToString(token.kind);
        this.addFailure(token.end - tokenText.length, end, Rule.FAILURE_STRING_FACTORY(tokenText), this.createMissingBraceFix(statement, node, sameLine));
    }
};
/** Generate the necessary replacement to add braces to a statement that needs them. */

How to use typescript.ScriptSnapshot:

43
44
45
46
47
48
49
50
51
52

    file = { version: 0, text };
    files.set(fileName, file);
  }

  return ts.ScriptSnapshot.fromString(file.text);
},
getCurrentDirectory: () => process.cwd(),
getCompilationSettings: () => compilerOptions,
getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),

How to use typescript.resolveTypeReferenceDirective:

351
352
353
354
355
356
357
358
359
360
        return resolvedModule;
    });
}
resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile, redirectedReference) {
    return typeReferenceDirectiveNames.map(moduleName => {
        const { resolvedTypeReferenceDirective } = ts.resolveTypeReferenceDirective(moduleName, utils_1.workaroundResolve(containingFile), this._options, this, redirectedReference);
        if (this._options.enableIvy && resolvedTypeReferenceDirective && this.ngccProcessor) {
            this.ngccProcessor.processModule(moduleName, resolvedTypeReferenceDirective);
        }
        return resolvedTypeReferenceDirective;

How to use typescript.isSetAccessorDeclaration:

163
164
165
166
167
168
169
170
171
172
        validateParameterPropertyDeclaration(walkContext, node);
    }
    else if (properties && typescript_1.isPropertyDeclaration(node)) {
        validatePropertyDeclaration(walkContext, node);
    }
    else if (setters && typescript_1.isSetAccessorDeclaration(node)) {
        validateSetAccessorDeclaration(walkContext, node);
    }
};
var canIgnoreDecorator = function (walkContext, decoratorName, optionKey) {

How to use typescript.isPropertyDeclaration:

160
161
162
163
164
165
166
167
168
169
    validateParameterDeclaration(walkContext, node);
}
else if (parameterProperties && typescript_1.isParameterPropertyDeclaration(node, node.parent)) {
    validateParameterPropertyDeclaration(walkContext, node);
}
else if (properties && typescript_1.isPropertyDeclaration(node)) {
    validatePropertyDeclaration(walkContext, node);
}
else if (setters && typescript_1.isSetAccessorDeclaration(node)) {
    validateSetAccessorDeclaration(walkContext, node);

How to use typescript.createImportSpecifier:

68
69
70
71
72
73
74
75
76
77
    });
    if (hasImportAlready) {
        return ops;
    }
    // Just pick the first one and insert at the end of its identifier list.
    ops.push(new interfaces_1.AddNodeOperation(sourceFile, maybeImports[0].elements[maybeImports[0].elements.length - 1], undefined, ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))));
}
else {
    // Create the new import node.
    const namedImports = ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))]);

How to use typescript.isExternalModule:

30
31
32
33
34
35
36
37
38
39
var BlockScopeAwareRuleWalker = /** @class */ (function (_super) {
    tslib_1.__extends(BlockScopeAwareRuleWalker, _super);
    function BlockScopeAwareRuleWalker(sourceFile, options) {
        var _this = _super.call(this, sourceFile, options) || this;
        // initialize with global scope if file is not a module
        _this.blockScopeStack = ts.isExternalModule(sourceFile)
            ? []
            : [_this.createBlockScope(sourceFile)];
        return _this;
    }

How to use typescript.isVariableDeclarationList:

446
447
448
449
450
451
452
453
454
455
function variableIsAfterFirstInDeclarationList(node) {
    var parent = node.parent;
    if (parent === undefined) {
        return false;
    }
    return ts.isVariableDeclarationList(parent) && node !== parent.declarations[0];
}
function describeDocumentationFailure(node, docType) {
    var description = Rule.FAILURE_STRING_EXIST;
    if (node.modifiers !== undefined) {

How to use typescript.createNamedImports:

72
73
74
75
76
77
78
79
80
81
    // Just pick the first one and insert at the end of its identifier list.
    ops.push(new interfaces_1.AddNodeOperation(sourceFile, maybeImports[0].elements[maybeImports[0].elements.length - 1], undefined, ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))));
}
else {
    // Create the new import node.
    const namedImports = ts.createNamedImports([ts.createImportSpecifier(undefined, ts.createIdentifier(symbolName))]);
    const importClause = ts.createImportClause(undefined, namedImports);
    const newImport = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(modulePath));
    if (allImports.length > 0) {
        // Find the last import and insert after.

How to use typescript.OperationCanceledException:

27
28
29
30
31
32
33
34
35
36
    isCancellationRequested() {
        return this._isCancelled;
    }
    throwIfCancellationRequested() {
        if (this.isCancellationRequested()) {
            throw new ts.OperationCanceledException();
        }
    }
}
exports.CancellationToken = CancellationToken;

How to use typescript.isParameterPropertyDeclaration:

157
158
159
160
161
162
163
164
165
166
    validateMethodDeclaration(walkContext, node);
}
else if (parameters && typescript_1.isParameter(node) && !typescript_1.isParameterPropertyDeclaration(node, node.parent)) {
    validateParameterDeclaration(walkContext, node);
}
else if (parameterProperties && typescript_1.isParameterPropertyDeclaration(node, node.parent)) {
    validateParameterPropertyDeclaration(walkContext, node);
}
else if (properties && typescript_1.isPropertyDeclaration(node)) {
    validatePropertyDeclaration(walkContext, node);

How to use typescript.isParameter:

154
155
156
157
158
159
160
161
162
163
    validateGetAccessorDeclaration(walkContext, node);
}
else if (methods && typescript_1.isMethodDeclaration(node)) {
    validateMethodDeclaration(walkContext, node);
}
else if (parameters && typescript_1.isParameter(node) && !typescript_1.isParameterPropertyDeclaration(node, node.parent)) {
    validateParameterDeclaration(walkContext, node);
}
else if (parameterProperties && typescript_1.isParameterPropertyDeclaration(node, node.parent)) {
    validateParameterPropertyDeclaration(walkContext, node);

How to use typescript.isMethodDeclaration:

151
152
153
154
155
156
157
158
159
160
var callbackHandler = function (walkContext, node) {
    var _a = walkContext, _b = _a.options, getters = _b.getters, methods = _b.methods, _c = OPTION_PARAMETER_PROPERTIES, parameterProperties = _b[_c], parameters = _b.parameters, properties = _b.properties, setters = _b.setters;
    if (getters && typescript_1.isGetAccessorDeclaration(node)) {
        validateGetAccessorDeclaration(walkContext, node);
    }
    else if (methods && typescript_1.isMethodDeclaration(node)) {
        validateMethodDeclaration(walkContext, node);
    }
    else if (parameters && typescript_1.isParameter(node) && !typescript_1.isParameterPropertyDeclaration(node, node.parent)) {
        validateParameterDeclaration(walkContext, node);

How to use typescript.isGetAccessorDeclaration:

148
149
150
151
152
153
154
155
156
157
    return Rule;
}(rules_1.AbstractRule));
exports.Rule = Rule;
var callbackHandler = function (walkContext, node) {
    var _a = walkContext, _b = _a.options, getters = _b.getters, methods = _b.methods, _c = OPTION_PARAMETER_PROPERTIES, parameterProperties = _b[_c], parameters = _b.parameters, properties = _b.properties, setters = _b.setters;
    if (getters && typescript_1.isGetAccessorDeclaration(node)) {
        validateGetAccessorDeclaration(walkContext, node);
    }
    else if (methods && typescript_1.isMethodDeclaration(node)) {
        validateMethodDeclaration(walkContext, node);

How to use typescript.isBlock:

85
86
87
88
89
90
91
92
93
94
let wrapperBody;
if (ts.isFunctionExpression(potentialClass.expression)) {
    wrapperBody = potentialClass.expression.body;
}
else if (ts.isArrowFunction(potentialClass.expression)
    && ts.isBlock(potentialClass.expression.body)) {
    wrapperBody = potentialClass.expression.body;
}
else {
    return false;

How to use typescript.isAccessor:

55
56
57
58
59
60
61
62
63
64
        .map(utils_2.getDecoratorName)
        .filter(isNotNullOrUndefined_1.isNotNullOrUndefined)
        .find(utils_2.isAngularClassDecorator);
};
var isDeclarationLike = function (node) {
    return typescript_1.isAccessor(node) || typescript_1.isMethodDeclaration(node) || typescript_1.isParameterPropertyDeclaration(node, node.parent) || typescript_1.isPropertyDeclaration(node);
};
var validateDeclaration = function (walkContext, node) {
    var klass = utils_2.getNextToLastParentNode(node);
    var classDecoratorName = getClassDecoratorName(klass);

How to use typescript.isArrayLiteralExpression:

9
10
11
12
13
14
15
16
17
18
}
exports.getAnimations = getAnimations;
function getInlineStyle(dec) {
    return astQuery_1.decoratorArgument(dec).bind(function (expr) {
        var property = expr.properties.find(function (p) { return astQuery_1.isProperty('styles', p); });
        return astQuery_1.getInitializer(property).fmap(function (expr) { return (expr && ts.isArrayLiteralExpression(expr) ? expr : undefined); });
    });
}
exports.getInlineStyle = getInlineStyle;
function getTemplate(dec) {

How to use typescript.updateDefaultClause:

42
43
44
45
46
47
48
49
50
51
        case ts.SyntaxKind.ModuleBlock:
            return ts.updateModuleBlock(node, result);
        case ts.SyntaxKind.CaseClause:
            return ts.updateCaseClause(node, node.expression, result);
        case ts.SyntaxKind.DefaultClause:
            return ts.updateDefaultClause(node, result);
        default:
            return node;
    }
}

How to use typescript.getSyntheticLeadingComments:

32
33
34
35
36
37
38
39
40
41
exports.addPureComment = addPureComment;
function hasPureComment(node) {
    if (!node) {
        return false;
    }
    const leadingComment = ts.getSyntheticLeadingComments(node);
    return !!leadingComment && leadingComment.some(comment => comment.text === pureFunctionComment);
}
exports.hasPureComment = hasPureComment;
function isHelperName(name) {

How to use typescript.isComputedPropertyName:

66
67
68
69
70
71
72
73
74
75
    return ts.updateDecorator(node, ts.updateCall(decoratorFactory, decoratorFactory.expression, decoratorFactory.typeArguments, [
        ts.updateObjectLiteral(objectExpression, properties),
    ]));
}
function visitComponentMetadata(node, styleReplacements, directTemplateLoading, resourceImportDeclarations, moduleKind) {
    if (!ts.isPropertyAssignment(node) || ts.isComputedPropertyName(node.name)) {
        return node;
    }
    const name = node.name.text;
    switch (name) {

How to use typescript.addSyntheticLeadingComment:

25
26
27
28
29
30
31
32
33
34
    ts.forEachChild(node, helper);
    return nodes;
}
exports.collectDeepNodes = collectDeepNodes;
function addPureComment(node) {
    return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, pureFunctionComment, false);
}
exports.addPureComment = addPureComment;
function hasPureComment(node) {
    if (!node) {

How to use typescript.setTextRange:

33
34
35
36
37
38
39
40
41
42
if (isBlockLike(node)) {
    let result = visitBlockStatements(node.statements, context);
    if (result === node.statements) {
        return node;
    }
    result = ts.setTextRange(result, node.statements);
    switch (node.kind) {
        case ts.SyntaxKind.Block:
            return ts.updateBlock(node, result);
        case ts.SyntaxKind.ModuleBlock:

How to use typescript.createImmediatelyInvokedFunctionExpression:

296
297
298
299
300
301
302
303
304
305
    : hostNode;
const innerVarStmt = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([
    ts.createVariableDeclaration(name, undefined, literalInitializer),
]));
const innerReturn = ts.createReturn(ts.createIdentifier(name));
const iife = ts.createImmediatelyInvokedFunctionExpression([
    innerVarStmt,
    ...statements,
    innerReturn,
]);

How to use typescript.createBlock:

407
408
409
410
411
412
413
414
415
416
        ],
        undefined,
        [],
        undefined,
        undefined,
        ts.createBlock(wrappedStatements)
    ),
    undefined,
    undefined
)

How to use typescript.createArrowFunction:

397
398
399
400
401
402
403
404
405
406
...(hasTLA
    ? // If there is a top-level await, wrap all non-hoisted statements in (async () => { ... })();
    [
        ts.createExpressionStatement(
            ts.createCall(
                ts.createArrowFunction(
                    [
                        ts.createModifier(
                            ts.SyntaxKind.AsyncKeyword
                        ),

How to use typescript.formatDiagnostics:

5
6
7
8
9
10
11
12
13
14
// Print error diagnostics.
const hasError = diagnostics.some(diag => diag.category === ts.DiagnosticCategory.Error);
if (hasError) {
    // Throw only if we're in strict mode, otherwise return original content.
    if (strict) {
        const errorMessages = ts.formatDiagnostics(diagnostics, {
            getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
            getNewLine: () => ts.sys.newLine,
            getCanonicalFileName: (f) => f,
        });

How to use typescript.createVariableDeclarationList:

317
318
319
320
321
322
323
324
325
326
]));
const modifiers = hostNode.modifiers;
const isDefault = !!modifiers
    && modifiers.some(x => x.kind === ts.SyntaxKind.DefaultKeyword);
const newStatement = [];
newStatement.push(ts.createVariableStatement(isDefault ? undefined : modifiers, ts.createVariableDeclarationList([
    ts.createVariableDeclaration(name, undefined, pureIife),
], ts.NodeFlags.Let)));
if (isDefault) {
    newStatement.push(ts.createExportAssignment(undefined, undefined, false, ts.createIdentifier(name)));

How to use typescript.isVariableStatement:

182
183
184
185
186
187
188
189
190
191
192


/** @param {import("typescript").Statement} s */
function canBeExported(s) {
    return (
        // const, let, var
        ts.isVariableStatement(s) ||
        // type, interface, enum, class, function
        ts.isTypeAliasDeclaration(s) ||
        ts.isInterfaceDeclaration(s) ||
        ts.isEnumDeclaration(s) ||

How to use typescript.createPropertyAccess:

131
132
133
134
135
136
137
138
139
140
if (!url) {
    return null;
}
const urlLiteral = ts.createLiteral(url);
if (moduleKind < ts.ModuleKind.ES2015) {
    return ts.createPropertyAccess(ts.createCall(ts.createIdentifier('require'), [], [urlLiteral]), 'default');
}
else {
    const importName = ts.createIdentifier(`__NG_CLI_RESOURCE__${resourceImportDeclarations.length}`);
    resourceImportDeclarations.push(ts.createImportDeclaration(undefined, undefined, ts.createImportClause(importName, undefined), urlLiteral));

How to use typescript.createNamespaceImport:

13
14
15
16
17
18
19
20
21
22
function insertStarImport(sourceFile, identifier, modulePath, target, before = false) {
    const ops = [];
    const allImports = ast_helpers_1.collectDeepNodes(sourceFile, ts.SyntaxKind.ImportDeclaration);
    // We don't need to verify if the symbol is already imported, star imports should be unique.
    // Create the new import node.
    const namespaceImport = ts.createNamespaceImport(identifier);
    const importClause = ts.createImportClause(undefined, namespaceImport);
    const newImport = ts.createImportDeclaration(undefined, undefined, importClause, ts.createLiteral(modulePath));
    if (target) {
        ops.push(new interfaces_1.AddNodeOperation(sourceFile, target, before ? newImport : undefined, before ? undefined : newImport));

typescript functions:

Sorted by popularity