简体   繁体   English

如何为现有的全局函数提供TypeScript批注

[英]How to provide TypeScript annotation to existing global function

I'm considering adding TypeScript type annotations to an existing project. 我正在考虑将TypeScript类型注释添加到现有项目。 I'm having trouble providing an external declaration file for a very simple example: 我在为一个非常简单的示例提供外部声明文件时遇到了麻烦:

program.ts : program.ts

/// <reference path="types.d.ts"/>

function greet (p) {
    console.log(p.name);
}

var x = {name: 'Mary'};

greet(x);

types.d.ts : types.d.ts

interface Person {
    height?: number,
    name: string
}

declare function greet (p: Person): void;

I expected this to work but I'm getting the following error: 我希望这能正常工作,但出现以下错误:

program.ts(3,10): error TS2384: Overload signatures must all be ambient or non-ambient.

It seems to think that the function definition is an overload and not the implementation of a previous declaration. 似乎认为函数定义是重载,而不是先前声明的实现。

What is the right way to add a type to the greet function? greet函数添加类型的正确方法是什么?

Requirement: the program.ts should be plain JavaScript, eg, free from any type annotations. 要求: program.ts应该是纯JavaScript,例如,没有任何类型注释。

This isn't supported or allowed by the language. 该语言不支持或不允许这样做。 Essentially the code is doing... 本质上,代码正在执行...

interface Person {
    height?: number,
    name: string
}

declare function greet(p: Person): void;

function greet(p: any): void {
    console.log(p.name);
}

So you get that error for defining a function and ambient function with the same name. 因此,使用相同名称定义函数和环境函数时会出现该错误。

What is the right way to add a type to the greet function? 向greet函数添加类型的正确方法是什么?

It's to do this: 为此:

interface Person {
    height?: number,
    name: string
}

function greet(p: Person): void {
    console.log(p.name);
}

Requirement: the program.ts should be plain JavaScript, eg, free from any type annotations. 要求:program.ts应该是纯JavaScript,例如,没有任何类型注释。

This isn't possible without changing the code in program.ts . 如果不更改program.ts中的代码,这是不可能的。 One possibility is to change program.ts to program.js then describe program.js with a declaration file for use in other files. 一种可能是将program.ts更改为program.js,然后使用声明文件描述program.js ,以供其他文件使用。 That would only mean other files using program.js could benefit from knowing the type and structure of that file, but it wouldn't stop you from making mistakes in program.js . 这仅意味着使用program.js的其他文件可以从了解该文件的类型和结构中受益,但不会阻止您在program.js中犯错误。

Note that the main purpose of definition files is to provide type information for code found in .js files—not .ts files. 请注意,定义文件的主要目的是为.js文件(而非.ts文件)中找到的代码提供类型信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM