TypeScript Literal Types
Introduction
Literals are /exact/ values that are JavaScript primitives.
Types
- [TypeScript String Literal Type](TypeScript String Literal Type)
- [TypeScript Boolean Literal Type](TypeScript Boolean Literal Type)
- [TypeScript Number Literal Type](TypeScript Number Literal Type)
- [TypeScript Template Literal String Type](TypeScript Template Literal String Type)
Type Guards
- [TypeScript Literal Type Guard](TypeScript Literal Type Guard)
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 src_typescript{{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!