I think you’re looking for the const assertion, added in TS 3.4.
You just need to add as const
to the string for it to become a literal type.
const x = {
y: 'def' as const,
};
const z: { y: 'def' } = x; // no error :)
More Related Contents:
- TypeScript: Object.keys return string[]
- Create a global variable in TypeScript
- Way to tell TypeScript compiler Array.prototype.filter removes certain types from an array?
- What does the “as const” mean in TypeScript and what is its use case?
- Typescript: Check “typeof” against custom type
- Angular2 – should private variables be accessible in the template?
- Typescript check object by type or interface at runtime with typeguards in 2020+
- How to use fetch in TypeScript
- Typescript property does not exist on union type
- Typescript primitive types: any difference between the types “number” and “Number” (is TSC case-insensitive)?
- Specify method’s type without converting the method to property
- Default parameters with generics in TypeScript
- How to watch and reload ts-node when TypeScript files change
- Can’t import CSS/SCSS modules. TypeScript says “Cannot Find Module”
- Changing Property Name in Typescript Mapped Type
- Unable to import svg files in typescript
- Typescript 2.0. “types” field in tsconfig.json
- Merge Two Interfaces
- NextJS getStaticProps() never called
- Integrating Material Design Lite with Angular2
- How excess property check helps?
- ts-node ignores d.ts files while tsc successfully compiles the project
- how to remove properties via mapped type in TypeScript
- TypeScript sorting an array
- “An index signature parameter type cannot be a union type.” – what should I use instead?
- Detailed differences between type annotation `variable: type` and type assertion `expression as type` in TypeScript
- Generic and typeof T in the parameters
- How to make “handler” lookup for “dispatcher” style function be typed correctly
- How to define an interface for objects with dynamic keys?
- Modules vs. Namespaces: What is the correct way to organize a large typescript project?