gpt4 book ai didi

javascript - 如何为现有的全局函数提供 TypeScript 注释

转载 作者:行者123 更新时间:2023-11-30 16:02:22 30 4
gpt4 key购买 nike

我正在考虑向现有项目添加 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):错误 TS2384:过载签名必须全部为环境或非环境。

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

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

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

最佳答案

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

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 文件中的代码提供类型信息。

关于javascript - 如何为现有的全局函数提供 TypeScript 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37530898/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com