Home > Net >  TypeScript define variable type when getting value implicitly
TypeScript define variable type when getting value implicitly

Time:09-25

If I do something like this in javascript

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

How do I do the same in TypeScript to be able to define the types that those variables will have?

CodePudding user response:

You can either type props:

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

Or the spread object:

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

Both will correctly infer the types of peer, users and otherProps.

CodePudding user response:

You have two ways to destruct you object with types,

1 :

const { peer, users }: { peer: string; users: Array<any> } = props

2 : Or you can create a type or interface for that data:

 interface Data {
  peer: string
  users: Array<any>
}

then use it :

const data: Data = props
  • Related