Typescript 在使用let的情况下,是什么导致错误?
在使用let的情况下,错误提示显示“类型”(x:number)=>number)中缺少属性'increment',但类型'Incrementor'中需要属性'increment'。 但是,在使用常量的情况下,它不会显示 在本例中使用let和const有什么区别 以下是原始代码:Typescript 在使用let的情况下,是什么导致错误?,typescript,typescript-typings,Typescript,Typescript Typings,在使用let的情况下,错误提示显示“类型”(x:number)=>number)中缺少属性'increment',但类型'Incrementor'中需要属性'increment'。 但是,在使用常量的情况下,它不会显示 在本例中使用let和const有什么区别 以下是原始代码: 这与let和const无关,boo和foo都应该显示错误,因为您正在使用函数not Incrementor初始化它们 interface Incrementor { (x: number): number; in
这与let和const无关,boo和foo都应该显示错误,因为您正在使用函数not Incrementor初始化它们
interface Incrementor {
(x: number): number;
increment: number;
}
const a: Incrementor = function (x) { return 111 };
a.increment = 111;
let a1: Incrementor = function (x) { return 111 };
a1.increment = 111;
const boo:Incrementor=function(x){return 111};// 这似乎是一个bug,我不知道Typescript对const变量做了什么,我找到了一种方法来纠正这个例子中的错误:let a1:Incrementor=function(x){return 11}as Incrementor代码>这里的boo和foo都应该用函数初始化,因为接口Incrementor描述了函数类型。如果你使用[index:string]:any
而不是increment:number
,它会工作,但仍然会作弊。但如果您将其更改为[index:string]:number,它将抛出error@SerhiiBilyk当然,[index:string]:any允许空键值
const boo: Incrementor = function (x) { return 111 }; // <- Error
let foo: Incrementor = function (x) { return 111 }; // <- Error