首页 > 解决方案 > 将字符串转换为对象属性名称

问题描述

我已经看到一个类似的问题询问这个关于 javascript 的问题。但是,我需要打字稿中的答案,但我不知道该怎么做。将字符串值转换为对象属性名称

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

此外,我正在尝试创建一个接口,string[]其中每个元素都是具有所需属性名称和值类型的字符串。使用数组元素设置新对象的字段。正因为如此,我事先不会知道我的属性将是什么,因此我为什么要尝试找到一种方法来创建具有给定属性的新接口。

标签: typescript

解决方案


那是因为 typescript 推断出的类型madeObject{}(空对象)。只需给它一个更明确的类型

interface MyObject {
    title:string;
}

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

如果你知道一个对象会有键,但你不知道键的名称(可能是因为它们只在运行时才知道),那么你可以使用 typescripts 动态键

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';

解决此问题的另一种方法是一起删除类型安全(不推荐这样做,并且会使打字稿失去其用途)

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

推荐阅读