type和interface的区别

106 阅读1分钟

问题

定义了一个key-value的类型,key的类型是一个联合类型

type serverKey = 'configServer' | 'mongos' | 'shards' | 'servers';
export interface IServerInfo {
  [key in serverKey]: IInstanceListItem[];
}

然后在业务代码中进行调用

const [instanceList, setInstanceList] = useState<IServerInfo | null>(null);
setInstanceList({});

首先感觉异常是因为我在写对象的时候vscode并没有给出提示。然后尝试设置了一个serverKey以外的key值,vscode竟然也没有出现报错。

后来把这段类型定义放到了TypeScript的playground中试了一下竟然报错了

A mapped type may not declare properties or methods.(7061)

原因

TODO

解决方法

将IServerInfo前面的interface换成type

type serverKey = 'configServer' | 'mongos' | 'shards' | 'servers';
export type IServerInfo = {
  [key in serverKey]: IInstanceListItem[];
};

Partial

TODO

参考资料

ts官方文档:www.typescriptlang.org/docs/handbo…

stackoverflow:s://stackoverflow.com/questions/70652935/