在类型记录中,似乎有两种方法可以在接口中声明命名函数:
export interface Zoo {
foo(): string
readonly bar: () => string,
}两个问题:
更新:
下面是一个较长的例子:
export interface Zoo {
foo(): string
readonly bar: () => string,
}
export const x: Zoo = {
foo: () => "a",
bar: () => "a",
};
x.foo = () => "b"; // No error
x.bar = () => "b"; // Error: Cannot assign to "bar"在我看来,这两种声明方式似乎是等价的,除了第二种方式可以是可读的。
我还发现了this的旧答案,说它们是等价的,除了过载的可能性。
发布于 2017-05-13 13:19:28
它们都是有效的,并生成相同的Javascript代码:
exports.x = {
foo: function () { return "a"; },
bar: function () { return "a"; }
};但实际上,您只能将readonly修饰符分配给属性。
旧的答案仍然有效,第一个答案可以用来过载,第二个答案是否定的:
a.ts(2,5): error TS2300: Duplicate identifier 'myFunction'.
a.ts(3,5): error TS2300: Duplicate identifier 'myFunction'.
a.ts(3,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'myFunction' must be of type '(s: string) => void', but here has type '(s: number) => void'.概括地说:
在编译了代码之后,没有。在此之前,类型记录使用bar作为属性,使用fpo作为函数。
因为函数不能有只读修饰符
https://stackoverflow.com/questions/43952660
复制相似问题