我有一个像这样的带标签的联盟
type FieldValue =
| { type: “multiple-choice”, content: string[] }
| { type: “text”, content: string }我想要有一个“智能结构”功能
function default<T extends FieldValue>(): T {
...
}它将返回以下两个参数之一
{ type: “multiple-choice”, content: [] }或
{ type: “text”, content: “” }基于类型T。现在,我知道我不能在运行时访问泛型类型,但也许有一种更好的方法来实现这一点(接口?条件类型?类?)。
有什么方法可以省去我自己手工编写defaultText和defaultMultipleChoice的工作吗?
发布于 2020-09-17 00:04:22
也许你可以换个方式,看看这是否有帮助:
const MultipleChoice = {
type: 'multiple-choice' as const,
content: [] as string[]
}
const SingleChoice = {
type: 'text' as const,
content: ''
}
type MultipleChoice = typeof MultipleChoice
type SingleChoice = typeof SingleChoice
type FieldValue = MultipleChoice | SingleChoicehttps://stackoverflow.com/questions/63923701
复制相似问题