簡體   English   中英

無法聲明多個自定義命名屬性 TypeScript MUI v5 Palette

[英]Unable to declare multiple custom named properties TypeScript MUI v5 Palette

我正在嘗試設置許多自定義屬性,以使將來在語義上易於更新。 但是,我在 MUI v5 中擁有多個自定義屬性時遇到了問題

Ts 誤差

TS2717: Subsequent property declarations must have the same type. Property 'background' must be of type 'TypeBackground', but here has type 'PaletteColor'.

調色板.ts

export const palette = {
  primary: {
    light: '#6D6B8C',
    main: '#6514DD',
    dark: '#6D6B8C',
  },
  secondary: {
    main: '#6D6B8C',
  },
  error: {
    main: '#bd4646',
  },
  background: {
    main: '#fff',
    paper: '#F5F5F5',
  },
  border: {
    main: '#DADAE1',
    primary: '#DADAE1',
  },
  text: {
    primary: '#6D6B8C',
    secondary: '#000',
  },
}


declare module '@mui/material/styles' {
  interface Palette {
    border: Palette['primary']
    background: Palette['primary']
  }

  // allow configuration using `createTheme`
  interface PaletteOptions {
    border?: PaletteOptions['primary']
    background?: PaletteOptions['primary']
  }
}

在此處輸入圖像描述

您正在使用 TypeScript 的一項功能,稱為聲明合並 問題是因為接口的非函數成員應該是唯一的。 如果它們不是唯一的,則它們必須屬於同一類型(請參閱此處的文檔)。

順便說一句:使用declare module 'foo'來導入和合並現有對象稱為模塊擴充,這是一種特殊類型的聲明合並。 您實際上可以在同一個文件中合並兩個具有相同名稱的接口。


一個可能的解決方案

由於無法通過聲明合並來合並兩個不同類型的成員,因此一種替代方法可能是簡單地聲明一個新類型。

/// animal.ts
export interface Animal {
  name: string
  age: number
  birthday: string // goal: represent birthday as a `Date` instead of `string`
}


/// pet.ts
import { Animal } from './animal'

// remove the offending property from `Animal`, while simultaneously
// extending the new `Pet` type to add `birthday` back in as a `Date`
type Pet = Omit<Animal, 'birthday'> & {
  birthday: Date
  ownerId: number
}

// the compiler accepts the augmented definition of `Pet`
const pet: Pet = {
  name: 'fido',
  age: 2,
  birthday: new Date(), // see, not a string!
  ownerId: 1
}

解釋

由於declare module增加了額外的噪音,我將省略它以使示例更直觀。 考慮以下代碼片段:

/// animal.ts - good
export interface Animal {
  name: string
  age: number
}

export interface Animal {
  birthday: string
}

上述代碼在 TypeScript 中是完全允許的。 編譯器將Animal的兩個單獨聲明合並到一個定義中。

讓我們看一個不同的例子。

/// animal.ts - bad
export interface Animal {
  name: string
  age: number
  birthday: string
}

export interface Animal {
  birthday: Date
}

希望問題很明顯。 Animal的兩個聲明都有birthday ,但類型不同。 編譯器應該如何知道birthday應該是什么類型? 它可以做出一些假設,但幸運的是它沒有,而是寧願給出一個錯誤:

typescript: Subsequent property declarations must have the same type. Property 'birthday' must be of type 'string', but here has type 'Date'.

暫無
暫無

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

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