Chris Drackett
Chris Drackett

Reputation: 1327

is it possible to use generics in an object in typescript?

I'm trying to set the type of one object value based on the type of another value and I'm curious if this is possible. Given:

type KeyType = 'string' | 'number'
type ValueType = { string: string, number: number }

type TestObject<T extends KeyType> = {
  key: T
  args: ValueType[T]
}

const test1: TestObject = { key: 'string', value: 'hello' } // should be ok
const test2: TestObject = { key: 'number', value: 2 } // should be ok
const test3: TestObject = { key: 'string', value: 2 } // should fail, value should be string

is there a way to do this in typescript? I can only get this to work if I pass the generic to the type declaration. However I know in functions its possible for this to be inferred.

Upvotes: 1

Views: 38

Answers (1)

basarat
basarat

Reputation: 276333

is it possible to use generics in an object in typescript?

Yes. Here is the working code (you were close):

export type KeyType = 'string' | 'number'
type ValueType = { string: string, number: number }

type TestObject<T extends KeyType> = {
  key: T
  value: ValueType[T]
}

const testA: TestObject<'string'> = { key: 'string', value: 'hello' } // should be ok
const testB: TestObject<'number'> = { key: 'number', value: 2 } // should be ok
const testC: TestObject<'string'> = { key: 'string', value: 2 } // Error: value needs to be string

Showing the error: enter image description here

More

You need to specify the generic when using a generic as a type annotation e.g. TestObject<'number'>

Upvotes: 1

Related Questions