简体   繁体   中英

How to provide TypeScript annotation to existing global function

I'm considering adding TypeScript type annotations to an existing project. I'm having trouble providing an external declaration file for a very simple example:

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;

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?

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

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?

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.

This isn't possible without changing the code in 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. 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 .

Note that the main purpose of definition files is to provide type information for code found in .js files—not .ts files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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