DEV Community

Acid Coder
Acid Coder

Posted on • Updated on

Typescript WTF Moments 5: const a = 'a' is not equal to const a = 'a' as const and const a:'a'='a'

normally we can skip type annotation because we know that typescript will infer the type for us

but turn out the with or without type annotation does make a real different

const a = 'a' // 'a'
//    ^?
const c = [a] // string[]
//    ^?

const a1 = 'a' as const // 'a'
//    ^?
const c1 = [a1] // 'a'[]
//    ^?

const a2:'a' = 'a' // 'a'
//    ^?
const c2 = [a2] // 'a'[]
//    ^?
Enter fullscreen mode Exit fullscreen mode

notice that c is string[] while c2 and c3 are 'a'[]

playground

this is work as intended, read the explanation here

Top comments (0)