我正在使用 TypeScript,我想知道如何“鍵入”以下物件。
{
"code": 52,
"somerandomstring123":"Some Data"
}
問題是,KEY NAME somerandomstring123是動態生成的字串,不是常量。例如,JSON 可能是這樣的:
{
"code": 52,
"someOTHERstring456":"Some Data"
}
我試過這樣使用[key:string]: string:
interface SomeObjectData {
code: number;
[target: string]: string;
}
但它回傳一個錯誤: Property 'code' of type 'number' is not assignable to 'string' index type 'string'.
PS:動態命名屬性(例如 somerandomstring123)值型別是一個字串,所以 usingstring | number不是我需要的。
uj5u.com熱心網友回復:
試試這個:
type SomeObjectData = {
[key: string]: string; // dynamic properties
} & {
code: number; // static properties
};
uj5u.com熱心網友回復:
您可以為目標使用聯合型別。
interface SomeObjectData {
[target: string]: string | number;
code: number;
}
const data:SomeObjectData = { code: 12}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403367.html
標籤:
