我有一個非常基本的可區分聯合,但對于鑒別器,我只想允許來自另一個字串文字聯合型別的特定值。這將使向受歧視的工會添加新的工會“案例”變得更加容易。
這是一個字串文字聯合,它描述了該型別允許的“值”:
type AllowedType = "typeForNumber" | "typeForBoolean"
然后,我描述資料的型別使用該字串文字聯合:
type Data = {
type: AllowedType,
value: number | boolean
}
根據我的示例,有兩個選項,可以value根據其type欄位具有更具體的型別。我不使用這些選項,它們只是為了演示目的:
// Option 1 - "value" is a "number"
type DataOption1 = {
type: "typeForNumber",
value: number
}
// Option 2 - "value" is a "boolean"
type DataOption2 = {
type: "typeForBoolean",
value: boolean
}
所以我真正想做的是一個有區別的聯合Data,因為我可以通過這種方式為其value欄位提供更具體的型別:
type Data =
| {
type: "typeForNumber"
value: number
}
| {
type: "typeForBoolean"
value: boolean
}
當您使用該型別時,一切正常:
const myData: Data = {
type: "typeForNumber",
// this creates an error, should be a `number`
value: "some string"
}
My question is: How do I make sure that the type field in my Data type can only be one of the options of the AllowedType?
In the future, there will be more options for AllowedType, so I want to limit the possible union types with them.
One could change add another union to the Data type like so, without any error:
type Data =
| {
type: "typeForNumber"
value: number
}
| {
type: "typeForBoolean"
value: boolean
}
| {
type: "someOtherType"
value: string
}
This new union (with type: "someOtherType") shouldn't be allowed.
Is it possible to limit the discriminator (type) in this discriminated union (Data) from other string literal union type (AllowedType)?
I tried to use a wrapper for the intersection, but the unions ignore (overwrite?) the type type:
type AllowedType = "typeForNumber" | "typeForBoolean"
type DataWrapper = {
type: AllowedType
value: number | boolean
}
type Data = DataWrapper &
(
| {
type: "typeForNumber"
value: number
}
| {
type: "typeForBoolean"
value: boolean
}
)
uj5u.com熱心網友回復:
如果我理解正確,問題是Data并且AllowedType可能不同步。如果這是問題所在,您可以扭轉局面并根據 定義AllowedType,Data如下所示:
type Data =
| {
type: "typeForNumber"
value: number
}
| {
type: "typeForBoolean"
value: boolean
};
type AllowedType = Data["type"];
游樂場鏈接
然后,添加到Data自動添加到AllowedType.
在評論中,您曾說過您正在嘗試防止工會中type的拼寫錯誤:Data
在我的例子中,Data 型別代表來自另一個來源的動態資料,所以我想確保型別值中沒有錯別字(例如 typeForNumber)。這就是為什么我如此熱衷于找到將型別限制為特定值的解決方案。在我的情況下,扭轉它并沒有幫助。
這似乎對此有所幫助:
type CheckData<DataType extends {type: AllowedType}> =
Exclude<DataType["type"], AllowedType> extends never
? DataType
: never;
然后這個作業:
type Data = CheckData<
| {
type: "typeForNumber"
value: number
}
| {
type: "typeForBoolean"
value: boolean
}>;
但這不是:
type Data2 = CheckData<
| {
type: "typeForNumber"
value: number
}
| {
type: "typeForBoolean"
value: boolean
}
| {
type: "typeForSomethingElse"
value: boolean
}>;
游樂場鏈接
不過,它并沒有捕捉到所有的錯別字。它允許兩種型別都使用相同的type值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436897.html
