I'm working with a very complexe API and some fields are restrictives string (string of length X max). So I created this type:
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;
};
It work pretty well to create string with the format I want but there is the deal, I have to fill an object with this type but the max length on each key can be different and I need so to know what is the max length to write in the key of the object. Exemple:
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
};
If someone know how to deal with it thanks a lot ! :)