I have created a custom route type for my project url. The function accepts two parameters,
- actual path url
- param for the url. eg) “/project/:projectId/user/:userId” => {projectId:”…”,userId:”…”}
My second parameter (param) in the function can be undefined if there is no query path like project url in the code. But I find it difficult to add optional type when param type is undefiend. Anyone has better solution?
const projectDetailUrl = "/project/:id";
const projectUrl = "/project";
export type ExtractParams<T extends string> =
T extends `${infer _Start}:${infer Param}/${infer _End}`
? Param | ExtractParams<_End>
: T extends `${infer _Start}:${infer LastParam}`
? LastParam
: never;
export type CreateParamObject<T extends string> = ExtractParams<T> extends
| never
| undefined
? undefined
: {
[K in ExtractParams<T>]: string;
};
function push<T extends string>(url: T, params: CreateParamObject<T>) {
console.log(url)
console.log(params)
}
push(projectUrl,undefined)
push(projectDetailUrl,{id:"1"})
I want to removed undefiend without an error but keep params type if there is query path
AS IS
push(projectUrl,undefined)
push(projectDetailUrl,{id:"1"})
TO BE
push(projectUrl)
push(projectDetailUrl,{id:"1"})
고민영 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.