[TS] - const in typescript
Truong Bui
Published on:
•
Last updated:
Problem
type Brand = 'Mercedes' | 'Toyota' | 'Ferrari';
interface Car {
speed: number;
brand: Brand
}
function showCar(car: Car) { }
const mercedes = {
speed: 500,
brand: 'Mercedes'
}
showCar(mercedes)
// ^^^^^^^^
// Argument of type '{ speed: number; brand: string; }'
// is not assignable to parameter of type 'Car'.
// Types of property 'brand' are incompatible.
// Type 'string' is not assignable to type 'Brand'.(2345)
Library: typescript v5.2.2
Solution
type Brand = 'Mercedes' | 'Toyota' | 'Ferrari';
interface Car {
speed: number;
brand: Brand
}
function showCar(car: Car) { }
const mercedes = {
speed: 500,
- brand: 'Mercedes'
+ brand: 'Mercedes' as const
}
showCar(mercedes)
Library: typescript v5.2.2
Why ?
In typescript let or const has different behaviourlet brand = 'Mercedes';
// ^^^^^ brand: string // primitive type
const brand = 'Mercedes';
// ^^^^^ brand: 'Mercedes' // literal type
let car = { brand: 'Mercedes' };
// ^^^ car: { brand: string }
const car = { brand: 'Mercedes' };
// ^^^ car: { brand: string }
interface Car {
speed: number;
brand: Brand // branch is literal type, not a string
}
INFO:
There are some order ways to solve this problem
You can read more about literal type here
https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html
// use type assertion
const mercedes = {
speed: 500,
brand: 'Mercedes'
} as Car
// use type annotation
const mercedes: Car = {
speed: 500,
brand: 'Mercedes'
}
// use const
const mercedes = {
speed: 500,
brand: 'Mercedes'
} as const
const mercedes = {
speed: 500,
brand: 'Mercedes' as const
}
Hope you find this article useful. If you have any questions, please let me know in the comment section below. 👇