Home > Mobile >  Typescript object property from type definiton
Typescript object property from type definiton

Time:11-25

I'll describe the problem as simply as possible

I have a type composed of forced strings eg:

type myType = 'name' | 'age' | 'family' | 'other';

I'm going to create a type that forces me to write this

const myObject: myCastType<myType> = {
    name: 'string',
    age: 'string',
    family: 'string',
    other: 'string',
}

so what I would like to create myCastType

what I'm missing is the step that allows me to force an object to be composed of properties called by the passed types

to make you understand better I'm not interested in being able to create a type eg:

type Person = { name: string, age: string, family: string, other: string }

const myObject: Person = { ... }

My problem is that props like 'name', 'age', etc... don't know them and they change in the various implementation i want to do so i need to define them dynamically

I tried to search for something about it but no one mentions my problem or anything similar, but unfortunately I haven't found anything that can help me.

of course I tried things like Pick, Record, Extract, etc, basically a good part of those present on 'lis.es5.d.ts'

Does anyone have any ideas or can direct me to a more correct path. links, documentation or any material is welcome

CodePudding user response:

You'll be glad to know that the "cast type" already exists — Record:

type MyType = "name" | "age" | "family" | "other";

const myObject: Record<MyType, string> = {
    name: "string",
    age: "string",
    family: "string",
    other: "string",
};

Record<MyType, string> means "a record (object) with the property names from MyType [which can a a simple type or a union] and the values string."

If you left out any of those properties, TypeScript would complain the object wasn't valid.

Playground example

  • Related