如何解决打字稿可以在运行时检索幻像类型参数吗?
我正在使用一个非常复杂的 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 举报,一经查实,本站将立刻删除。