为什么类型脚本跟踪函数静态属性的突变? [英] Why does TypeScript track mutation of function static properties?
本文介绍了为什么类型脚本跟踪函数静态属性的突变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直认为打字脚本不会跟踪对象突变。 例如:
type DescribableObject = {
name: string;
age: number;
};
// error
const obj: DescribableObject = {
name: 'sdf'
}
obj.age = 2
但是,它似乎在某些情况下跟踪函数静态属性的突变。
type DescribableFunction = {
description: string;
(): boolean;
};
// error
const fn: DescribableFunction = () => true
//fn.description = 'hello';
如果取消注释//fn.description = 'hello';
,打字错误将消失。
此外,如果将鼠标悬停在fn
上,您将看到TS将fn
视为某种module
。
fn
函数是什么类型的模块?
是否记录了此行为?
推荐答案
从TypeScrip3.1开始,您可以define "expando" properties on functions。这是在microsoft/TypeScript#26368中实现的,作为对microsoft/TypeScript#15868的修复。显然,开发人员在JavaScript中向函数添加属性的模式很常见,但在此功能之前,在TypeScrip中还没有惯用的方法来实现这一点。
现在您可以这样做:
function foo(x: string) { foo.callCount++; return x.length }
foo.callCount = 0;
但在TypeScrip 3.1之前,您必须这样做:
function bar(x: string) { bar.callCount++; return x.length }
namespace bar {
export var callCount = 0;
}
或此:
const baz = Object.assign(
(x: string) => { baz.callCount++; return x.length },
{ callCount: 0 }
);
甚至是这个:
const qux = ((x: string) => { qux.callCount++; return x.length }) as
{ (x: string): number; callCount: number };
qux.callCount = 0;
所有这些都相当难看。
虽然像microsoft/TypeScript#12416中所要求的那样,允许在所有对象(如
DescribableObject
)而不仅仅是函数上使用扩展属性可能很好,但这似乎不是一个需要支持的常见或重要的模式。一般来说,您可以使用对象文字一次添加您想要的所有属性(尽管有时依赖项可能很难处理),但您不能使用函数来做到这一点。
这篇关于为什么类型脚本跟踪函数静态属性的突变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文