如果我在javascript中这样做
const { peer, users, ...otherProps } = props;
我如何在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
、users
和otherProps
的类型。
有两种方法可以用类型析构对象,
1:
const { peer, users }: { peer: string; users: Array<any> } = props
2:或者您可以为该数据创建一个类型或接口:
interface Data {
peer: string
users: Array<any>
}
然后使用:
const data: Data = props