带条件的Typescript递归泛型类型



对于通用函数,

function func<T>(arg:T):T {
return arg
}

从自变量推断出CCD_ 1

考虑这个用例:

type RecursiveType<OK extends boolean = false> = { // 1
isOK: OK;
property: OK extends true ? ("a"|"b") : 0;
children?: Array<RecursiveType>; // 2
}
const recursive:RecursiveType = {
isOK: true;
property: 'a',
children: [
{
isOK: false,
property: 0
},
{
isOK: true,
property: 'b'
},
]
}

TS抱怨Type 'true' is not assignable to type 'false'

但是,如果我删除默认类型,现在我必须为children的类型提供一个参数,否则为Generic type 'RecursiveType' requires 1 type argument(s).

如何正确地声明RecursiveType,以便在创建变量时,我的编辑器可以为property提供正确的类型提示?

有没有什么方法可以让ts像泛型函数一样推断OK的类型?

对于这种特定情况,您必须声明类型。因为推断是不合适的。

type RecursiveType<OK extends boolean = false> = { // 1
isOK: OK;
property: OK extends true ? ("a"|"b") : 0;
children?: Array<RecursiveType>; // 2
}
const recursive:RecursiveType<true> = {
isOK: true,
property: 'a',
children: [
{
isOK: false,
property: 0
}
]
}

最新更新