将字符串转换为对象属性名称

时间:2019-07-17 18:04:26

标签: typescript

我已经看到一个类似的问题,有关javascript的问题。但是,我需要打字稿中的答案,我不知道该怎么做。 Convert string value to object property name

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

此外,我尝试从string[]创建一个接口,其中每个元素都是具有所需属性名称和值类型的字符串。 Use elements of an array to set the fields of a new object。因此,我不会事先知道我的属性是什么,因此为什么我试图找到一种使用给定属性创建新接口的方法。

1 个答案:

答案 0 :(得分:2)

那是因为打字稿推断madeObject的类型为{}(空对象)。给它一个更明确的类型

interface MyObject {
    title:string;
}

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

如果您知道某个对象将具有键,但是您不知道键的名称(也许是因为它们仅在运行时才知道),则可以使用打字稿动态键

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