我對高級打字稿概念還很陌生,所以請耐心等待。我有許多專案使用物件通過一些常見的道具(例如_type)來映射反應組件。
我想要做的是自動回傳使用這些物件映射決議的組件的正確型別,但是any
當我嘗試這個時我只收到一個型別。
許多在線帖子建議使用 switch 陳述句(示例如下)。我們公司使用物件映射模式,所以我想盡可能避免使用 switch 陳述句。謝謝。為了增加背景關系,這是我們第一個使用 typescript(從 javascript 遷移)的 react 專案。
// types
type AnimalType = 'cat' | 'dog'
interface Cat {
_type: AnimalType
name: string
onMeow: () => void
}
interface Dog {
_type: AnimalType
name: string
onBark: () => void
}
type Animal = Cat | Dog
type AnimalMap = {
[property in Animal['_type']]
}
// THIS WORKS BUT WE DON'T WANT TO USE THIS
// resolving animal type via switch
const CatComponent = ({ _type, name, onMeow }: Cat) => <div>I'm a cat!</div>
const DogComponent = ({ _type, name, onBark }: Dog) => <div>I'm a dog!</div>
function resolveAnimal(_type: AnimalType): React.Component<Animal> {
switch(_type) {
case "dog": return DogComponent
case "cat": return CatComponent
}
return animalMap[_type]
}
// THIS DOESN'T WORK, WE'D LOVE TO USE THIS!
// resolving animal type via object map
const animalMap: AnimalMap = {
cat: CatComponent,
dog: DogComponent,
}
function resolveAnimal(_type: AnimalType): React.Component<Animal> {
return animalMap[_type]
}
function App() {
const ResolvedAnimalComponent = resolveAnimal('dog')
return <ResolvedAnimalComponent onBark={() => console.log('HE BARKED')} />
}
uj5u.com熱心網友回復:
洗掉顯式表示法,: AnimalMap
以便物件宣告值不會擴大 - 您希望 TypeScript 看到
const animalMap: {
cat: CatComponent,
dog: DogComponent,
}
不是
const animalMap: AnimalMap
(不僅因為您AnimalMap
沒有記下值 - 組件 - 還因為它沒有將屬性與其組件聯系起來)
利用
const animalMap = {
cat: CatComponent,
dog: DogComponent,
}
function resolveAnimal<T extends keyof typeof animalMap>(_type: T) {
return animalMap[_type]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496203.html
標籤:javascript 反应 打字稿 界面