我们的结构如下:
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,但其行为与上面的结构相似?
我试图使用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)
我希望这里有一个错误.有什么我缺少或在某种程度上滥用类型定义?