报错内容
此表达式不可调用。类型 "IServerListItem[]" 没有调用签名。ts(2349) Cannot invoke an expression whose type lacks a call signature
报错源码
const generateServerListForShardComponent = (
shard_component: ShardingComponentEnum,
data?:
| IBatchInstallInOneGroupServerList[]
| Record<string, IBatchInstallInOneGroupServerList[]>
) => {
if (Array.isArray(data)) {
return (
data?.map((item) => {
return {
...item,
shard_component
} as IServerListItem;
}) ?? []
);
} else {
return (
Object.keys(data ?? {}).map((key) => {
return {
...data?.[key],
shard_component,
shard_id: key
} as IServerListItem;
}) ?? []
);
}
};
//调用方法
const [serverListInfo, setServerListInfo] = useState<IServerListItem[]>();
if (res?.architecture === ArchitectureEnum.sharding) {
const configServerList = generateServerListForShardComponent(
ShardingComponentEnum['config-servers'],
res?.configServer
);
const mongosList = generateServerListForShardComponent(
ShardingComponentEnum.mongos,
res?.mongos
);
const shardList = generateServerListForShardComponent(
ShardingComponentEnum.shards,
res.shards
);
const temp: IServerListItem[] = [
...configServerList,
...mongosList,
...shardList
];
//这里报错了
serverListInfo(temp);
}
ts 2349原因
报错原因是一个实例的特定属性或者方法不能在他的预期类型上找到。错误理解变量类型,比如以为serverListInfo为setState类型的函数,但实际上在本段代码里他是一个state变量,所以这里报了错。
关于这个错误的其他一些问题
let labels: string[] | number[] = [];
labels.push(1);
let labels:(string|number)[]=[]
labels.push(1);
这里第一行会报错,第二行不会报错。原因为string[] | number[]和(string|number)[]并不相等,第一个labels的数组元素要么全是number要么全是string;第二个labels指的是数组元素可以为number也可以为string。
参考资料
github:github.com/Microsoft/T…
stackoverflow:stackoverflow.com/questions/3…