TypeScript对象解构取值时如何隐式定义提取变量的类型?
TypeScript 解构赋值的类型自动推导方案
如果你想让解构得到的变量自动获得对应类型(也就是你说的隐式定义类型),不需要挨个给变量单独标注类型,只要给被解构的源对象props 提前定义好完整类型即可。
推荐写法:提前定义源对象类型
- 先定义
props的完整类型结构,你可以根据实际业务调整属性类型:
// 示例类型,可替换为你实际需要的类型 interface Props { peer: string; // 比如可以是Peer连接实例类型 users: Array<{id: string; name: string}>; title: string; visible: boolean; // 其他属性的类型定义 }
- 给源对象
props标注上述类型后,解构得到的变量会自动继承对应类型:
// 以函数参数场景为例,先给参数props标注类型 function MyComponent(props: Props) { // peer自动获得string类型,users自动获得数组类型,otherProps自动包含title、visible属性及对应类型 const { peer, users, ...otherProps } = props; // 后续直接使用即可,TS会自动做类型校验,不需要额外给变量写类型 }
如果是其他场景,只要确保被解构的源对象有明确的类型标注即可:
const props: Props = getPropsFromApi(); const { peer, users, ...otherProps } = props;
临时标注写法:解构时同步定义结构类型
如果你不想提前单独定义Props接口,也可以在解构时直接给整个结构标注类型,同样不需要给单个变量写类型:
const { peer, users, ...otherProps }: { peer: string; users: Array<{id: string}>; [key: string]: unknown; // 剩余属性的类型定义,也可以写具体类型 } = props;
注意不要写
const { peer: string } = props这类写法,这在TS中会被识别为把peer重命名为string变量,不是给peer定义类型。
内容的提问来源于stack exchange,提问作者cclloyd
相关产品推荐
相关产品推荐

