gpt4 book ai didi

typescript - 在 Typescript 中,我创建了一个带有字符串字段的函数接口(interface),为什么实现必须是 const?

转载 作者:行者123 更新时间:2023-12-05 03:30:19 27 4
gpt4 key购买 nike

interface DescribableFunction  {
description: string;
(f: number,s:number): number;
};

function doSomething(fn: DescribableFunction) {
console.log( " returned " + fn(3,4));
}

//here,"const" is right,"let" will be error
const p:DescribableFunction=(first:number,second:number)=>first+second;
p.description="hello";

doSomething(p);

如果 DescribableFunction 没有“描述”字段,const 或 let 都可以我在 https://www.typescriptlang.org/play 测试它

最佳答案

Here you have a documentation :

TypeScript 3.1 brings the ability to define properties on function declarations and const-declared functions, simply by assigning to properties on these functions in the same scope. This allows us to write canonical JavaScript code without resorting to namespace hacks. For example:

function readImage(path: string, callback: (err: any, image: Image) => void) {
// ...
}
readImage.sync = (path: string) => {
const contents = fs.readFileSync(path);
return decodeImageSync(contents);
};

所以,这是设计决策。

关于typescript - 在 Typescript 中,我创建了一个带有字符串字段的函数接口(interface),为什么实现必须是 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70846284/

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