基于功能参数的条件类型检查

时间:2020-08-17 15:30:01

标签: reactjs typescript firebase

我正在编写一个自定义的Hook,该Hook可以使用一个或两个字符串,或者是一个具有更精细参数的对象。我想添加一个条件类型检查,以检查该参数的类型并基于该参数做一些逻辑。以下是相关片段:

// The hook itself
const [error, loading, data] = useFirestore('posts', 'test'); // in a string version
const [error, loading, data] = useFirestore({...someProps}); // in a object version version
// The types that i defined for them
type queryType<T> = T extends string ? string : documentQueryType;
type docType<T> = T extends string ? string : never;

type documentQueryType = {
    collection: string;
    query: string[] | string[][];
    limit: number;
    orderBy: string; // todo limit this to be only special words
    order: string; // todo same as above
    startAt: number;
    endAt: number;
};
// The function that is in the question
export const useFirestore = <T>(query: queryType<T>, doc?: docType<T>) => {...rest of the function

我将如何使最后一个代码段起作用,以便在传递对象时将doc设置为从不,而在传递字符串时将doc设置为字符串?

1 个答案:

答案 0 :(得分:0)

这可以使用条件类型部分实现,但可能不是100%类型安全的。由于table1(url_id, affichew)是可选的,因此在docquery时不需要,并且在string是对象时仍将允许undefined

但是,如果这两种情况都不成问题,则可以使用条件类型来实现:

query