簡體   English   中英

在 Typescript 中獲取自動完成的顯式鍵名

[英]Get explicit key names for autocompletion in Typescript

我想要做的是給定一個特定類型的 object,將其傳遞給 function,完全刪除mobileweb部件,具體取決於我告訴它保留哪個部件,然后刪除將其內容向上移動到移動/網絡父級下方。 這張圖片將證明這一點。 在此處輸入圖像描述 我已經簡化了示例以減少代碼,所以如果它看起來毫無意義,那可能就是原因。

因此,當我擁有 object 時,它應該看起來像這樣

const newObj: NewTypeCreated = {
  key1: {
    width: 150,
    height: 400,
  },
  key2: {
    width: 100,
  },
};

我已經使用此代碼

const customComponentsStyle = (
  comps: ResponsiveCustomComponentsStyle,
  mobileOrWeb: 'mobile' | 'web',
) =>
  Object.keys(comps).reduce((newObj, currentKey) => {
    const { width, height, maxHeight } = customComponents[currentKey][mobileOrWeb]!;
    const newObject = {
      ...(width && { width }),
      ...(height && { height }),
      ...(maxHeight && { maxHeight }),
    };

    return {
      ...newObj,
      [currentKey]: newObject,
    };
  }, {});

const x = customComponentsStyle(customComponents, 'mobile');
console.log(x);

//Output
{ key1: { width: 150, height: 400 }, key2: { width: 100 } }

問題是x上沒有自動完成功能,它不知道上面有什么。

console.log(x.key1.width);

ts error
Property 'key1' does not exist on type '{}'.ts(2339)

誰能在這里指出我正確的方向? 我只想能夠執行 x 並根據新的對象類型進行適當的自動完成。

您可以明確告訴 Typescript customComponentsStyle返回NewTypeCreated類型的數據:

const customComponentsStyle = (
  comps: ResponsiveCustomComponentsStyle,
  mobileOrWeb: 'mobile' | 'web',
): NewTypeCreated => {
  ...
}

這將告訴 Typescript customComponentsStyle返回一個帶有字符串屬性的 object ,其中每個屬性都是一個 object , widthheight為可選數字。

您可以在下面添加這些類型

type KeyType = {
  width?: number
  height?: number
}

type ReturnType = {
  key1?: KeyType
  key2?: KeyType
}

並更改customComponentsStyle function 像這個代碼截圖

const customComponentsStyle = (
  comps: ResponsiveCustomComponentsStyle,
  mobileOrWeb: 'mobile' | 'web',
): ReturnType =>
  Object.keys(comps).reduce((newObj, currentKey) => {
    const { width, height, maxHeight } = customComponents[currentKey][mobileOrWeb]!;
    const newObject = {
      ...(width && { width }),
      ...(height && { height }),
      ...(maxHeight && { maxHeight }),
    };

    return {
      ...newObj,
      [currentKey]: newObject,
    };
  }, {} as ReturnType);

暫無
暫無

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

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