How to use typescript - 10 common examples

To help you get started, we’ve selected a few typescript examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tensorflow / tfjs / tfjs-core / scripts / test_snippets / util.ts View on Github external
async function visit(
    // tslint:disable-next-line:no-any
    tf: any, checker: ts.TypeChecker, node: ts.Node,
    sourceFile: ts.SourceFile) {
  const children = node.getChildren();
  for (let i = 0; i < children.length; i++) {
    await visit(tf, checker, children[i], sourceFile);
  }

  if (ts.isClassDeclaration(node) || ts.isFunctionDeclaration(node) ||
      ts.isMethodDeclaration(node) || ts.isInterfaceDeclaration(node)) {
    const symbol = checker.getSymbolAtLocation(node.name);
    const jsdoc = getJSDocTag(symbol);
    if (jsdoc == null) {
      return;
    }
    // Ignore snippets of methods that have been marked with ignoreCI.
    if (jsdoc['ignoreCI']) {
      return;
    }

    const documentation = symbol.getDocumentationComment(checker);
    if (documentation == null) {
      return;
    }
    for (let i = 0; i < documentation.length; i++) {
github microsoft / vscode / build / monaco / api.js View on Github external
case ts.SyntaxKind.VariableStatement:
            case ts.SyntaxKind.TypeAliasDeclaration:
            case ts.SyntaxKind.FunctionDeclaration:
            case ts.SyntaxKind.ModuleDeclaration:
                stop = visitor(node);
        }
        // if (node.kind !== ts.SyntaxKind.SourceFile) {
        // 	if (getNodeText(sourceFile, node).indexOf('SymbolKind') >= 0) {
        // 		console.log('FOUND TEXT IN NODE: ' + ts.SyntaxKind[node.kind]);
        // 		console.log(getNodeText(sourceFile, node));
        // 	}
        // }
        if (stop) {
            return;
        }
        ts.forEachChild(node, visit);
    };
    visit(sourceFile);
github neo-one-suite / neo-one / gulp.js View on Github external
const compileTypescript = ({
  source,
  entries,
}: {|
  source: string,
  entries: Array,
|}) => {
  const options = getCompilerOptions(source);
  const host = ts.createCompilerHost(options);
  host.resolveModuleNames = resolveModuleNames(options);
  const program = ts.createProgram(
    getTypescriptFiles(source, entries),
    getCompilerOptions(source),
    host,
  );
  const emitResult = program.emit();

  const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);

  allDiagnostics.forEach(diagnostic => {
    if (diagnostic.file) {
      const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
      const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
      // eslint-disable-next-line
      console.log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
    }
    else {
github tambien / Piano / scripts / tsc-then-webpack.ts View on Github external
let options = {
        outDir: compilerOptions.outDir,
        module: ts.ModuleKind[compilerOptions.module.toUpperCase()],
        target: ts.ScriptTarget[compilerOptions.target.toUpperCase()],
        sourceMap: compilerOptions.sourceMap
    };
    // let options = {
    //     outDir: compilerOptions.outDir,
    //     module: ts.ModuleKind.ES2015,
    //     target: ts.ScriptTarget.ES2017,
    //     sourceMap: compilerOptions.sourceMap
    // };
    console.log('options: ', options);
    const tsfiles = fs.readdirSync('ts').map(f => `ts/${f}`);
    console.log('tsfiles: ', tsfiles);
    const program = ts.createProgram(tsfiles, options);
    const emitResult = program.emit();
    /*
    
    const allDiagnostics = ts
        .getPreEmitDiagnostics(program)
        .concat(emitResult.diagnostics);
    
    allDiagnostics.forEach(diagnostic => {
        if (diagnostic.file) {
            let {line, character} = diagnostic.file.getLineAndCharacterOfPosition(
                diagnostic.start
            );
            let message = ts.flattenDiagnosticMessageText(
                diagnostic.messageText,
                "\n"
            );
github dotansimha / graphql-code-generator / packages / utils / config-md-generator / src / index.ts View on Github external
export async function generateConfig(inputFile: string): Promise {
  const program: ts.Program = ts.createProgram([inputFile], {
    target: ts.ScriptTarget.ES5,
    downlevelIteration: true,
    allowSyntheticDefaultImports: true,
    lib: ['es6', 'esnext', 'es2015', 'dom'],
    moduleResolution: ts.ModuleResolutionKind.NodeJs,
    module: ts.ModuleKind.CommonJS,
  });

  const compilerDiagnostics: ReadonlyArray = program.getSemanticDiagnostics();
  if (compilerDiagnostics.length > 0) {
    for (const diagnostic of compilerDiagnostics) {
      const message: string = ts.flattenDiagnosticMessageText(diagnostic.messageText, os.EOL);
      if (diagnostic.file) {
        const location: ts.LineAndCharacter = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!);
        const formattedMessage: string = `${diagnostic.file.fileName}(${location.line + 1},${location.character + 1}):` + ` [TypeScript] ${message}`;
        // tslint:disable-next-line:no-console
        console.error(formattedMessage);
github angular / angular / packages / compiler-cli / src / ngtsc / typecheck / src / environment.ts View on Github external
reference(ref: Reference>): ts.Expression {
    const ngExpr = this.refEmitter.emit(ref, this.contextFile);

    // Use `translateExpression` to convert the `Expression` into a `ts.Expression`.
    return translateExpression(
        ngExpr, this.importManager, NOOP_DEFAULT_IMPORT_RECORDER, ts.ScriptTarget.ES2015);
  }
github Bearer / bearer-js / packages / openapi-generator / src / index.ts View on Github external
export function functionTypesToSchemaConverter(
  functionPath: string,
  options: ts.CompilerOptions = { target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS }
): TOutput {
  const program = ts.createProgram([functionPath], options)
  const sourceFile = program.getSourceFile(functionPath)
  const checker = program.getTypeChecker()

  const output: TOutput = {
    requestBody: {},
    response: {}
  }

  if (sourceFile) {
    ts.forEachChild(sourceFile, visit)
  }

  return output

  function visit(node: ts.Node) {
    // Only consider exported nodes
github MichaReiser / speedy.js / packages / compiler / src / code-generation / value / undefined.ts View on Github external
castImplicit(type: ts.Type, context: CodeGenerationContext): Value | any {
        if (type.flags & ts.TypeFlags.BooleanLike) {
            return Primitive.false(context, type);
        }

        if (type.flags & ts.TypeFlags.IntLike) {
            return new Primitive(llvm.ConstantInt.get(context.llvmContext, 0), type);
        }

        if (type.flags & ts.TypeFlags.NumberLike) {
            return new Primitive(llvm.ConstantFP.getNaN(llvm.Type.getDoubleTy(context.llvmContext)), type);
        }

        // cast pointer
        if (type.flags & ts.TypeFlags.Object || isMaybeObjectType(type) || type.flags & ts.TypeFlags.Undefined) {
            return new Undefined(context.builder.createBitCast(this.generateIR(context), context.toLLVMType(type)));
        }

        return undefined;
    }
github angular / angular / packages / compiler-cli / src / transformers / lower_expressions.ts View on Github external
const exportName = nodeRequest.name;
          declarations.push({name: exportName, node, order: DeclarationOrder.BeforeStmt});
          return ts.createIdentifier(exportName);
        }
        let result = node;
        if (shouldVisit(pos, end) && !isLexicalScope(node)) {
          result = ts.visitEachChild(node, visitNode, context);
        }
        return result;
      }

      // Get the original node before tsickle
      const {pos, end} = ts.getOriginalNode(node);
      let resultStmt: ts.Statement;
      if (shouldVisit(pos, end)) {
        resultStmt = ts.visitEachChild(node, visitNode, context);
      } else {
        resultStmt = node;
      }

      if (declarations.length) {
        inserts.push({relativeTo: resultStmt, declarations});
      }
      return resultStmt;
    }
github palantir / tslint / src / rules / variableNameRule.ts View on Github external
break;
            }

            case ts.SyntaxKind.VariableStatement:
                // skip 'declare' keywords
                if (tsutils.hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword)) {
                    return;
                }
                break;

            case ts.SyntaxKind.Parameter:
            case ts.SyntaxKind.PropertyDeclaration:
                handleDeclaredVariable(node as ts.ParameterDeclaration | ts.PropertyDeclaration);
                break;

            case ts.SyntaxKind.VariableDeclaration:
                handleVariableDeclaration(node as ts.VariableDeclaration);
        }

        return ts.forEachChild(node, cb);
    });