philk
philk

Reputation: 2140

Derive keys from strings in array in typescript to define object property names

I want to define the keys in an object match a 2-dimensional arrays first items.

export const ProductInfos = [
  ["description", "Description"],
] as const
type ProductInfoTypes = typeof ProductInfos[number][0]

export type Product = {
  id: string
  //[key in typeof ProductInfos[number][0]]: string
}

So here Product should end up with a property `description" that accepts a string.

However my [key in typeof ProductInfos[number][0]]: string does not compile

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)

Upvotes: 2

Views: 764

Answers (1)

Eldar
Eldar

Reputation: 10790

You can use built-in type mapper Record and type intersection like below:

export const ProductInfos = [
  ["description", "Description"],
] as const
type ProductInfoTypes = typeof ProductInfos[number][0]

type ProdcutDescription =  Record<ProductInfoTypes,string>

 type Base = {
  id: string
}

type Product = Base & ProdcutDescription

const product : Product ={
  id:"asdsa",
  description : "as" //ok 
foo:"ere" // error
}

Playground Link

Upvotes: 1

Related Questions