我有這種形式的輸入資料:
const input = {
postcode: ['0000']
submitted: ['yes']
}
const output = {
postcode: '0000'
submitted: 'yes'
}
如何為輸入資料創建介面?
我試過了:
interface inputData {
postcode: string[]
submitted: string[]
}
interface outputData {
postcode: string
submitted: string
}
但是我在應用它時遇到錯誤:
const extract = (input: inputData[]): outputData => {
for (const key in input) {
if (Object.hasOwnProperty.call(input, key)) {
input[key] = input[key][0]; // Error here
}
}
const output: any = input;
return output;
}
錯誤:Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'inputData'. Property '0' does not exist on type 'inputData'.
uj5u.com熱心網友回復:
這是一個作業版本
function hasOwnProperty<X extends {}, Y extends PropertyKey>
(obj: X, prop: Y): obj is X & Record<Y, unknown> {
return obj.hasOwnProperty(prop)
}
interface inputData {
postcode: string[];
submitted: string[];
}
type outputData = inputData;
const extract = (input: inputData): outputData => {
for (const key in input) {
if (hasOwnProperty(input, key)) {
const value = input[key];
if (value instanceof Array) {
input[key] = value[0];
}
}
}
const output: any = input;
return output;
}
uj5u.com熱心網友回復:
根據您提供的資訊,型別inputData是 Record<string,string[]>` Record 是實用程式型別(Link)
postcode: ['0000'],
submitted: ['yes']
}
type inputDataT = Record<string,string[]>
interface inputData {
postcode: string[]
submitted: string[]
}
const extract = (input: inputDataT) => {
const output: any = input;
for (const key in input) {
if (Object.hasOwnProperty.call(input, key)) {
output[key] = input[key][0];
}
}
return output;
}
console.log(extract(inputData))
此外,如果您確定屬性值陣列中只有一個字串,您可以按如下方式使其更強大:
type inputDataT = Record<string,[string]>
const inputData:inputDataT = {
postcode: ['0000'],
submitted: ['yes']
}
操場
uj5u.com熱心網友回復:
您可以使用索引器定義介面:
interface EnumServiceGetOrderBy {
[index: number]: { id: number; label: string; key: any };
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/490044.html
上一篇:如何從<ItemsControl.ItemTemplate><DataTemplate>更改代碼中的邊框寬度和高度
