Home > Mobile >  what is & in typescript and javascript?
what is & in typescript and javascript?

Time:06-06

i saw this in the someone else's code. (this is props of react component.) i know & is AND logical operater. i think & has another meaning in this code. when i use center = {{latitude: number,longitude: number},{zoom: 2, tilt: 2,}} it is not worked and i know not match vaild format with typescript error.

  1. what is & mean in this?
  2. how to vaild object format in center props(i use react.)?
export interface Coord {
    latitude: number;
    longitude: number;
}
center?: Coord & { zoom?: number; tilt?: number; bearing?: number };

CodePudding user response:

The & is Intersection Type

Basically, it lets you combine types

like the final object center should contain all those keys mentioned in

 { zoom?: number; tilt?: number; bearing?: number, latitude, longitude };

official doc : https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types

The reason that this

center = {{latitude: number,longitude: number},{zoom: 2, tilt: 2,}}

didn't work is that , first its not a valid object , second all the keys mentioned ( { zoom?: number; tilt?: number; bearing?: number, latitude, longitude } ) should be present in the object

  • Related