打字稿可以在运行时检索幻像类型参数吗?

问题描述

我正在使用一个非常复杂的 API,有些字段是限制性字符串(长度为 X 最大值的字符串)。所以我创建了这种类型:

import {isstring} from "lodash";

export type StringOfMaxLength<Max> = string & {
    readonly StringOfMaxLength: unique symbol;
};

export const isstringOfMaxLength = <Max extends number>(s: string,m: Max): s is StringOfMaxLength<Max> => s.length <= m;

export const stringOfMaxLengthBuilder = <Max extends number>(
    input: string,max: Max,): StringOfMaxLength<Max> => {
    if (!isstring(input)) {
        throw new Error("the input is not a string");
    }
    else if (!isstringOfMaxLength(input,max)) {
        throw new Error("The string is too long");
    }
    return input;
};

用我想要的格式创建字符串效果很好,但有一个交易, 我必须用这种类型填充一个对象,但每个键的最大长度可能不同,我需要知道写入对象键的最大长度是多少。 示例:

interface Obj {
randomKey: StringOfMaxLength<2>; // here it's 2 but I want to create a generic function that work with all value possible
};

const obj: Obj = {
randomKey: stringOfMaxLengthBuilder("hi",2) // here it work but I have to specify the length and my objectiv is to not specify it
};

如果有人知道如何处理,非常感谢! :)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)