首页 > 解决方案 > TypeScript 在隐式获取值时定义变量类型

问题描述

如果我在 javascript 中做这样的事情

const { peer, users, ...otherProps } = props;

我如何在 TypeScript 中做同样的事情才能定义这些变量将具有的类型?

标签: typescript

解决方案


您可以键入props

interface TypeOfProps {
    peer: string;
    users: number;
    randomProp: string;
}
const props: TypeOfProps = {
    peer: "peer",
    users: 5,
    randomProp: "hah"
}
const { peer, users, ...otherProps } = props;

或传播对象:

const { peer, users, ...otherProps}: TypeOfProps = props;

两者都将正确推断 和的peer类型。usersotherProps


推荐阅读