I want to combine both having a type for a constant, and using it "as const" to get the literal types as the type:
type MyType = {name: string};
const x:MyType = {
name: 'test' // Autocompleted, typesafe. But Type is {name: string}, not
// what I want, {name: 'test'}
}
const x = { name: 'test' } as const; // Gives correct type, but no type check...
How to do this?
Here is a way to achieve what you want:
type MyType = { name: string }
// This function does nothing. It just helps with typing
const makeMyType = <T extends MyType>(o: T) => o
const x = makeMyType({
name: 'test', // Autocompleted, typesafe
} as const)
x.name // type is 'name' (not string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With