【发布时间】:2020-08-09 21:39:48
【问题描述】:
我正在尝试在 Typescript 中使用泛型来实现策略模式。这个想法是让一个映射器具有所有可能类型的键,然后该值将具有该特定类型所需的所有问题(将使用 React 呈现)(稍后将扩展为还具有验证和其他相关内容)类型)。
这些是应用模式的对象
export interface Book {
id: string;
type: string;
title: string;
author: string;
}
export interface Novel extends Book {
genre: string;
}
这是问题的输入
export interface BookQuestionProps<T> {
book: T;
}
//implementation
export const titleQuestion: React.FunctionComponent<BookQuestionProps<Book>> = ({
book
}: BookQuestionProps<Book>) => {
return <input type="text" value={book.title} />
}
export const genreQuestion: React.FunctionComponent<BookQuestionProps<Novel>> = ({
book
}: BookQuestionProps<Novel>) => {
return <input type="text" value={book.genre} />
}
这是模式的主要部分
export interface BookMapperStrategy<T> {
questions: React.FunctionComponent<BookQuestionProps<Book>>[]
}
export interface BookTypeMapperStrategy<T> {
[type: string]: BookMapperStrategy<T>;
}
完成所有设置后,实现看起来像这样
//specific strategy for novel
const novelQuestions: React.FunctionComponent<BookQuestionProps<Novel>>[] = [
titleQuestion,
genreQuestion
]
const novelMapperStrategy: BookMapperStrategy<Novel> = {
questions: novelQuestions
}
// setup strategy pattern mapper
const bookTypeMapperStrategy: BookTypeMapperStrategy<Book> = {
novel: novelMapperStrategy,
}
//print questions
const novel: Novel = {
id: '',
type: 'novel',
title: '',
author: '',
genre: ''
}
bookTypeMapperStrategy[novel.type].questions.map((question) => {
React.createElement(question, {
novel
})
})
Typescript 然后在novelQuestions 上给我一个编译错误,特别是在以下数组中设置titleQuestion 时:
Type 'FunctionComponent<BookQuestionProps<Book>>' is not assignable to type 'FunctionComponent<BookQuestionProps<Novel>>'.
The types of 'propTypes.book' are incompatible between these types.
Type 'Validator<Book>' is not assignable to type 'Validator<Novel>'.
Type 'Book' is not assignable to type 'Novel'.ts(2322)
我尝试将接口更改为联合类型,但它给出了更多错误。
我原以为Novel 是Book 的孩子,传入React.FunctionComponent<BookQuestionProps<Book>> 类型的titleQuestion 成为React.FunctionComponent<BookQuestionProps<Novel>> 的一部分会起作用,因为Book 是@987654334 的父母@?
【问题讨论】:
标签: reactjs typescript typescript-typings typescript-generics