2

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)

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that was quick. I knew about the Record but didn't think of using it with intersection. TIL
How to make description optional in Product?
Sorry, already found answer to my question: type Product = Base & Partial<ProductDescription>
@basil you can use Partial to achieve what you want: type ProdcutDescription = Partial< Record<ProductInfoTypes,string>>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.