2016-05-30 45 views
1

我正在考虑将TypeScript类型注释添加到现有项目。 我有提供外部声明文件为一个非常简单的例子麻烦:如何向现有全局函数提供TypeScript注释

program.ts

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

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

var x = {name: 'Mary'}; 

greet(x); 

types.d.ts

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

declare function greet (p: Person): void; 

我预计这工作,但我得到以下错误:

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

它似乎认为函数定义是一个重载而不是以前的声明的实现。

greet函数添加到类型的正确方法是什么?

要求:program.ts应该是普通的JavaScript,例如没有任何类型的注释。

回答

1

这不受该语言支持或允许。本质上,代码正在做...

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

declare function greet(p: Person): void; 

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

所以你得到那个错误,定义一个函数和具有相同名称的环境函数。

What is the right way to add a type to the greet function?

这是要做到这一点:

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

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

Requirement: the program.ts should be plain JavaScript, e.g., free from any type annotations.

这也不是没有可能在program.ts改变代码。一种可能性是将program.ts更改为program.js然后描述program.js带有用于其他文件的声明文件。这只会意味着使用program.js的其他文件可以从了解该文件的类型和结构中受益,但它不会阻止您在program.js中犯错误。

请注意,定义文件的主要目的是为在.js文件中找到的代码提供类型信息,而不是.ts文件。

+0

描述'program.js'而不改变扩展名为'.ts'听起来像是正确的做法,因为我试图扩展现有的代码库。太糟糕了,那么就没有完整的安全性。无论如何,很好的答案! – btx9000

相关问题