相关疑难解决方法(0)

如何创建类似于Partial的,需要设置单个属性

我们的结构如下:

export type LinkRestSource = {
    model: string;
    rel?: string;
    title?: string;
} | {
    model?: string;
    rel: string;
    title?: string;
} | {
    model?: string;
    rel?: string;
    title: string;
};
Run Code Online (Sandbox Code Playgroud)

这几乎与说法相同

type LinkRestSource = Partial<{model: string, rel: string, title: string}>
Run Code Online (Sandbox Code Playgroud)

除了这将允许传入空对象,而初始类型需要传递其中一个属性

我怎样才能创建类似的泛型Partial,但其行为与上面的结构相似?

generics typescript

16
推荐指数
4
解决办法
4051
查看次数

Typescript Discriminated Union允许无效状态

我试图使用Typescript Discriminated Union来模拟异步加载数据时的一个相当常见的场景:

type LoadingState = { isLoading: true; }
type SuccessState = { isLoading: false; isSuccess: true; }
type ErrorState =   { isLoading: false; isSuccess: false; errorMessage: string; }

type State = LoadingState | SuccessState | ErrorState;
Run Code Online (Sandbox Code Playgroud)

根据我的理解,这应该根据类型定义限制允许的值组合.但是,类型系统很乐意接受以下组合:

const testState: State = {
    isLoading: true,
    isSuccess: true,
    errorMessage: "Error!"
}
Run Code Online (Sandbox Code Playgroud)

我希望这里有一个错误.有什么我缺少或在某种程度上滥用类型定义?

discriminated-union typescript

8
推荐指数
1
解决办法
471
查看次数

标签 统计

typescript ×2

discriminated-union ×1

generics ×1