'Typescript Intersection / Union / Partial / assertion magic
I have the following type:
export interface SphericalPolarCoordinate {
/**
*
* @param ϕ - the azimuth / right ascension (in degrees)
*
*/
ϕ: number
/**
*
* @param θ - the altitude / declination (in degrees)
*
*/
θ: number
}
Which I use in the following function:
export const getAngularSeparation = (
coord1: SphericalPolarCoordinate,
coord2: SphericalPolarCoordinate
): number => {
// Convert to radians:
const ϕ1 = convertDegreeToRadian(coord1.ϕ)
const θ1 = convertDegreeToRadian(coord1.θ)
const ϕ2 = convertDegreeToRadian(coord2.ϕ)
const θ2 = convertDegreeToRadian(coord2.θ)
...
}
However, I want to be able to pass in either of the two following types:
export type HorizontalCoordinate = {
/**
*
* is the angle of the object around the horizon, usually measured from true north
* and increasing eastward
*
*/
az: number
/**
*
* Altitude is the angular distance of an object above the local horizon
*
*/
alt: number
}
or
export type EquatorialCoordinate = {
/**
*
* right ascension, in astronomy, the east–west coordinate by which the position
* of a celestial body is ordinarily measured; more precisely, it is the angular
* distance of a body's hour circle east of the vernal equinox, measured along
* the celestial equator (in unit degrees)
*
*/
ra: number
/**
*
* angular distance north or south from the celestial equator measured along a
* great circle passing through the celestial poles (in unit degrees)
*
*/
dec: number
}
And perform some mapping / Typescript Union / Partial / casting magic, or assertion magic, to be able to pass in any Coordinate that loosely matches the SphericalPolarCoordinate base ...
Would anyone have an idea as to how this could be achieved?
I'm thinking it is something along the lines of:
type MappedTypeWithNewProperties<Type> = {
[Properties in keyof Type as NewKeyType]: Type[Properties]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
