Skip to content

Instantly share code, notes, and snippets.

@jaycosaur
Last active August 9, 2020 23:17
Show Gist options
  • Save jaycosaur/6c04a851b575520d5e305c9ce0775d5a to your computer and use it in GitHub Desktop.
Save jaycosaur/6c04a851b575520d5e305c9ce0775d5a to your computer and use it in GitHub Desktop.
Working around implicit conversions [typescript] - Typescript to Python field guide
type Celsius = {
type: "celsius";
value: number;
};
const celsius = (value: number): Celsius => ({
value,
type: "celsius",
});
type Fahrenheit = {
type: "fahrenheit";
value: number;
};
const fahrenheit = (value: number): Fahrenheit => ({
value,
type: "fahrenheit",
});
type Temperature = Celsius | Fahrenheit;
function convertToCelsius(value: Fahrenheit): Celsius {
return celsius((value.value * 9) / 5 + 32);
}
function convertToFahrenheit(value: Celsius): Fahrenheit {
return fahrenheit(((value.value - 32) * 5) / 9);
}
const converted = convertToCelsius(0); // Argument of type '0' is not assignable to parameter of type 'Fahrenheit'
const fahrenheitValue: Fahrenheit = fahrenheit(32);
convertToFahrenheit(fahrenheitValue); // Argument of type 'Fahrenheit' is not assignable to parameter of type 'Celsius'.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment