TypeScript Literal Types
Introduction
Literals are exact values that are JavaScript primitives.
Types
Type Guards
Inference
TypeScript is not all knowing. The following won't fly:
function iTakeFoo(foo: "foo") {}
const test = {
someProp: "foo",
}
iTakeFoo(test.someProp) // Error: Argument of type string is not assignable to parameter of type 'foo'
TypeScript infers test
to be of type {someProp: string
}. There are a
couple of ways to fix this:
function iTakeFoo(foo: "foo") {}
const test = {
someProp: "foo" as "foo",
}
iTakeFoo(test.someProp) // Okay!
function iTakeFoo(foo: "foo") {}
type Test = {
someProp: "foo"
}
const test: Test = {
// Annotate - inferred someProp is always === 'foo'
someProp: "foo",
}
iTakeFoo(test.someProp) // Okay!