我试图使用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)
我希望这里有一个错误.有什么我缺少或在某种程度上滥用类型定义?
我有以下带有通用参数的 React 功能组件:
type Props<T, S> = {
data: T[]
additionalData: S
}
function Component<T, S = void>({
....
Run Code Online (Sandbox Code Playgroud)
您可以按如下方式使用它:
<Component<Bike, BikeShed> data={bikes} additionalData={bikeShed} />
Run Code Online (Sandbox Code Playgroud)
由于第二个通用参数是可选的,因此您必须按如下方式使用它:
<Component<Car> data={cars} additionalData={undefined} />
Run Code Online (Sandbox Code Playgroud)
现在问题来了。有没有办法省略,additionalData={undefined}因为这里显然没有使用它。
我尝试的是这样的:
type Props<T, S = void> = {
data: T[]
additionalData?: S
}
Run Code Online (Sandbox Code Playgroud)
但它实际上改变了S,S | undefined这不是一个理想的情况!
Props当可选通用参数为 时,我可以以不必指定其相关属性的方式设置吗void?
我想编写一种类型,它允许创建具有一些始终需要的核心属性和一个可选属性的对象,该属性imageUrl在定义为字符串时imageAltText也需要作为字符串,
{
id: "test",
imageUrl: "test",
imageAltText: "test"
}
Run Code Online (Sandbox Code Playgroud)
我还希望它能够工作,以便何时imageUrl未定义我不希望imageAltText被定义。
{
id: "test"
}
Run Code Online (Sandbox Code Playgroud)
我已将类型定义如下,
(
{
/** image url for the banner of the card. Will display a blue background without an image */
imageUrl?: undefined;
}
|
{
/** image url for the banner of the card. Will display a blue background without an image */
imageUrl: string;
/** alternative text for the banner image */
imageAltText: string;
}
) …Run Code Online (Sandbox Code Playgroud) 鉴于此代码,
interface TaskStartedEvent {
type: "started",
task: string
}
interface TaskLogEvent {
type: "log",
task: string,
message: string
}
interface TaskFailedEvent {
type: "failed",
task: string,
error?: string
}
interface FreeLog {
message: string | Error,
meta?: unknown
}
interface UndefinedTask {
task?: undefined
}
type TaskEvent = TaskStartedEvent | TaskLogEvent | TaskFailedEvent;
type RuntimeEvent = (FreeLog & UndefinedTask) | TaskEvent;
function foo(ev: RuntimeEvent) {
console.log(ev);
}
foo({ message: "bar", type: "log" });
Run Code Online (Sandbox Code Playgroud)
为什么 Typescript 编译器在这里没有失败?
我传递了一个type字段,所以它不能是一个(FreeLog …
可以说我有 3 种类型。A 型、B 型和 C 型
typeA 有 name 属性,而 typeB 和 typeC 没有
当我用类似的代码渲染它时;
interface propTypes {
post: typeA | typeB | typeC
}
..... some react code ....
return(
{post?.name && component})
Run Code Online (Sandbox Code Playgroud)
但它返回一个错误:“属性‘name’在类型‘typeA| typeB | typeC’上不存在
我尝试 post instanceof typeA 但它返回错误“typeA”仅引用类型,但在此处用作值。