Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to object property name

Tags:

typescript

I have seen a similar question asked about this problem for javascript. However, I need the answer in typescript and I can't figure out how to do it. Convert string value to object property name

let madeObject = {};
const fieldName = 'title';
madeObject[fieldName] = 'hello';

Also, I am trying to create an interface from a string[] where each element is a string with the desired property name and value type. Use elements of an array to set the fields of a new object. Because of this, I won't know before hand what my properties are going to be, hence why I am trying to find a way to create a new interface with the given properties.

like image 729
Matthew Guo Avatar asked Feb 04 '26 15:02

Matthew Guo


1 Answers

That's because typescript infers the type of madeObject to be {} (empty object). Just give it a more explicit type

interface MyObject {
    title:string;
}

let madeObject:Partial<MyObject> = {};
const fieldName:keyof MyObject = 'title';
madeObject[fieldName] = 'hello';

If you know that an object will have keys, but you don't know the name of the keys (maybe because they are only known at runtime), then you can use typescripts dynamic keys

interface MyObject {
    // left side is the type of the key (usually string or symbol)
    // right side is the type of the property (use "any" if you don't know)
    [key:string]: string; 
}

let madeObject:MyObject = {};
const fieldName:string = 'title';
madeObject[fieldName] = 'hello';

// Or you can make the interface Generic, if you have this situation a lot:

interface MyObjectGeneric <V = any, K = string> {
    [key:K]: V; 
}

let madeObject:MyObjectGeneric/* <string> */ = {}; // Adding <string> would narrow the return type down to string
const fieldName:string = 'title';
madeObject[fieldName] = 'hello';

Another way to solve this would be to remove the type safety all together (this is NOT recommended and makes typescript lose its purpose)

let madeObject:any = {}; // declares that madeObject could be anything
const fieldName = 'title';
madeObject[fieldName] = 'hello';

// alternatively:

let madeObject2 = {}; // Type inferred as "{}"
(madeObject2 as any)[fieldName] = 'hello'; // Removes type safety only temporarily for this statement
like image 140
pascalpuetz Avatar answered Feb 07 '26 18:02

pascalpuetz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!