interface ExampleType {
[key: string]: string | (() => string);
}
const testObj: ExampleType = {
firstName: "Peter",
lastName: "Parker",
gender: "male",
getFullName: () => "I am Peter Parker",
};
const { firstName, lastName, getFullName } = testObj;
console.log(getFullName()); // this does not works
if (typeof getFullName === "function") {
console.log(getFullName()) // this works
}
我收到以下错误:**此表达式不可调用。
并非所有类型为 'string | (() => string)' 是可调用的。
类型“字符串”没有调用签名。 **
最佳答案
通过说testObj: ExampleType
,你是说testObj
将是一个属性为 string
的对象或 () => string
.这是一个宽泛而薄弱的 promise 。但是,您确切地知道哪些属性将属于哪种类型。
解决方案一
告诉编译器你知道的一切。在 ExampleType
中包含具体的属性名称.
interface ExampleType {
firstName: string;
lastName: string;
gender: string;
getFullName: () => string;
}
const testObj: ExampleType = {
firstName: "Peter",
lastName: "Parker",
gender: "male",
getFullName: () => "I am Peter Parker",
};
const { firstName, lastName, getFullName } = testObj;
console.log(getFullName()); // this works
解决方案二如果你想使用
ExampleType
作为蓝图,但想要为您推断出特定属性,请使用辅助函数,如 specific
定义如下。interface ExampleType {
[key: string]: string | (() => string);
}
const specific = <T>() => <U extends T>(argument: U) => argument;
const testObj = specific<ExampleType>()({
firstName: "Peter",
lastName: "Parker",
gender: "male",
getFullName: () => "I am Peter Parker",
});
const { firstName, lastName, getFullName } = testObj;
console.log(getFullName()); // this works
关于Typescript 接口(interface) : Not all constituents of type 'string | (() => string)' are callable. 类型 'string' 没有调用签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62823059/