通用字符串上的打字稿条件类型

时间:2021-04-03 20:53:02

标签: typescript typescript-typings typescript-generics

我有一个 CodeGenBlock 类型,我想根据 typerootnull 还是将一些属性动态添加到对象的类型中别的东西:


type InternalCodeGenTypes = 'root' | 'null';

export type CodeGenBlock<
    In extends string,
    T extends In | InternalCodeGenTypes = In | InternalCodeGenTypes
> = {
    name: string;
    description: string;
    signifier: string;
    type: T;
    opts?: CodeGenBlock<T>[];
    data: T extends 'null' ? never : string | (() => string);
};

const myCodeBlock: CodeGenBlock<"userDefinedA" | "userDefinedB"> = {
    type: "null",
    // data is never never, I don't know why though
    // I was wondering on on how to get the actual value of type without having to pass "null" as a parameter to CodeGenBlock
    }

我尝试做泛型并使用 extends 对其进行测试,但这并不会检查实际传递的值,而是检查始终返回 true 的字符串列表。我对如何做到这一点感到困惑。

传入的类型是由软件的用户定义的,所以我不能预定义和暴露'root'和'null'也不起作用。

0 个答案:

没有答案