Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'as const' combined with type?

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?

like image 817
user2154768 Avatar asked Jun 20 '19 21:06

user2154768


1 Answers

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)
like image 152
Tom Esterez Avatar answered Feb 02 '23 05:02

Tom Esterez