Skip to content

Instantly share code, notes, and snippets.

@tokland
Last active November 3, 2019 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokland/9dcae2ac7a2143b654ebb22da9b43f16 to your computer and use it in GitHub Desktop.
Save tokland/9dcae2ac7a2143b654ebb22da9b43f16 to your computer and use it in GitHub Desktop.
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