[英]Typescript - after checking if optional property exists on object still errors
[英]Typescript infers object as never when checking if a conditional property exists
我有一個名為T
的類型,它接受泛型類型Str extends string
。 如果Str
擴展了"hello"
,那么類型T
應該有一個稱為B
的附加屬性。 像這樣的東西:
export type T<Str extends string> = {
A: number;
} & (Str extends "hello" ? { B?: number } : {});
基於該類型,它的行為如下:
type T1 = T<"hello">; // type T1 = { A: number; B?: number | undefined; }
type T2 = T<"world">; // type T2 = { A: number; }
現在,我想創建一個接受此類型作為參數的 function,並根據屬性B
的存在添加一個額外的邏輯:
function t<Type extends string>(arg: T<Type>) {
if ("B" in arg) {
// ...
}
}
雖然,我收到一個錯誤,即 if 語句中的arg
被視為never
。
如果您明確命名變體,它會起作用:
export type Test<Str extends string> = {
A: number;
} & (Str extends "hello" ? { B?: number } : { });
type HelloVariant = Test<"hello">;
function t<T extends (HelloVariant | Test<string>)>(arg: T) {
if ("B" in arg) {
console.log(arg.B);
}
}
實際上需要命名的是該字符串是“hello”的可能性。 這是更簡化的版本:
export type Test<Str extends string> = {
A: number;
} & (Str extends "hello" ? { B?: number } : { });
function t<T extends (Test<"hello"> | Test<string>)>(arg: T) {
if ("B" in arg) {
console.log(arg.B);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.