Today I created two new UnionTypes in my project.
You can see this types here in Code-Review: https://codereview.stackexchange.com/questions/223433/uniontypes-partialrequired-and-pickrequired
export type PartialRequired<T, K extends keyof T> = Partial<T> & Pick<Required<T>, K>;
export type PickRequired<T, K extends keyof T> = T & Pick<Required<T>, K>;
export type ForceId<T extends { id?: ID }, ID = number> = PickRequired<T, 'id'>;
Now I thought about to make the id
attribute renameable?!
I tried something like this:
export type ForceId<T extends { [key: ID_NAME]?: ID }, ID = number, ID_NAME extends string = 'id'> = PickRequired<T, ID_NAME>;
// ~~ ';' expected
But as you can see, this didn't work. Is there a way I can achive something like this?
So I can use ForceId<MyModel, string, 'uuid'>
=> { uuid: '123e4567-e89b-12d3-a456-426655440000' }
without create a new definition like ForceUuid
?
Edit:
The goal is the following:
I have some Models looking like this:
interface MyModel1 {
id?: number; // The identifier of Model 1
name: string;
age?: number;
alive?: boolean;
}
interface MyModel2 {
uuid?: string; // The identifier of Model 2
name: string;
age?: number;
alive?: boolean;
}
I don't want to change any code at runtime.
Now I want to use the ForceId
type.
// Works
const model1: ForceId<MyModel1> = {
id: 0,
name: "test",
age: 10
};
// Don't work
const model2: ForceId<MyModel2, string, "uuid"> = {
uuid: "123e4567-e89b-12d3-a456-426655440000",
name: "test",
age: 10
};