[英]Interface function with some properties (TypeScript)?
如何使用以下界面?
interface Something {
(n: number): void,
description: string
}
我试着写以下。
var sth: Something = {
description: "Description"
}
sth = (n: number) => {
console.log("Something");
}
或者
var sth: Something = {
(n: number) => {
console.log("Something");
},
description: "Description"
}
但他们都给出了错误。
您不能直接创建既是函数又具有其他属性的对象。 您必须分两步完成,首先创建一个函数,然后为其分配另一个 prop,然后将结果分配给您界面的一个变量:
interface Something {
(n: number): void;
description: string;
}
function fn(n: number) {}
fn.description = 'foo';
const h: Something = fn;
您可以通过以下几种方式之一来完成。 每个都适合具有属性的函数,但都是可行的,具体取决于用例:
没有用于创建具有属性的函数的语法。 你必须分开做:
var sth: Something = ((n: number) => {
console.log(n + 2);
}) as Something;
sth.description = "Description";
这里需要as Something
断言来告诉编译器将函数视为Something
,否则您无法添加description
。
Object.assign()
这允许一次声明所有内容:
var sth: Something = Object.assign(
(n: number) => {
console.log(n + 2);
},
{ description: "Description"}
);
Object.assign
被输入为返回any
所以类型声明sth: Something
确保之后它被视为正确的对象。
Object.defineProperty()
另一种创建对象并添加属性的方法。 如果需要,它允许对属性进行更多控制,例如使其不可写。
var sth: Something = Object.defineProperty(
(n: number) => {
console.log(n + 2);
},
"description",
{ value: "Description"}
) as Something;
因为Object.defineProperty()
的类型与第一个参数相同,所以需要as Something
断言。 所以它返回(n: number) => void
。
Object.defineProperties()
与Object.defineProperty()
非常相似,但允许一次配置多个属性。
var sth: Something = Object.defineProperties(
(n: number) => {
console.log(n + 2);
},
{
description: { value: "Description" }
}
) as Something;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.