簡體   English   中英

將字符串轉換為對象屬性名稱

[英]Convert string to object property name

我已經看到一個類似的問題問有關javascript的此問題。 但是,我需要打字稿中的答案,我不知道該怎么做。 將字符串值轉換為對象屬性名稱

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

另外,我正在嘗試從string[]創建一個接口,其中每個元素都是具有所需屬性名稱和值類型的字符串。 使用數組的元素設置新對象的字段 因此,我不會事先知道我的屬性是什么,因此為什么我試圖找到一種使用給定屬性創建新接口的方法。

這是因為madeObject推斷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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM