Last active
November 3, 2019 23:08
-
-
Save tokland/9dcae2ac7a2143b654ebb22da9b43f16 to your computer and use it in GitHub Desktop.
Alternative to https://dev.to/ninjah187/advanced-typescript-s-capabilities-in-real-life-scenario-593l
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Metric { | |
timestamp: Date; | |
temperature: number; | |
pressure: number; | |
humidity: number; | |
rain: number; | |
sun: number; | |
windDirection: number; | |
windVelocity: number; | |
dew: number; | |
} | |
type Diff<T, U> = T extends U ? never : T; | |
type MetricParam = Diff<keyof Metric, "timestamp">; | |
const metricValues: { [K in MetricParam]: number } = { | |
temperature: 1, | |
pressure: 2, | |
humidity: 8, | |
rain: 16, | |
sun: 32, | |
windDirection: 64, | |
windVelocity: 128, | |
dew: 256 | |
}; | |
// An alternative way to implement it is using a sorted list: | |
// const metricParams: MetricParam[] = ["temperature", "pressure", ...] | |
async function fetchMetrics<Param extends MetricParam>( | |
stationId: number, | |
metrics: Param[] | |
): Promise<Pick<Metric, Param>[]> { | |
return []; // Placeholder | |
} | |
async function main() { | |
const metrics = await fetchMetrics(1, ["temperature", "pressure"]); | |
metrics.forEach(metric => { | |
console.log(metric.temperature, metric.pressure); | |
// console.log(metric.sun) // Error | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment