Conditional Type Checking based on function parameter - reactjs

Im writing a custom Hook that can take either one or two strings, or an object with more granular parameters. I wanted to add a conditional type check to check for a type of that param and do some logic based on it. Here are the relevant snippets:
// 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
How would I make the last snippet work so when passed an object it sets doc to never, and when passed a string sets the doc to string?

This can be partially achieved with conditional types, but it may not be 100% type-safe. Since doc is optional, it will not be required when the query is a string, and will still allow undefined when query is an object.
However, if these two scenarios are not an issue, this can be achieved with conditional types:
// Simplified type
type DocumentQueryType = {
collection: string;
};
// The two types of queries that are accepted
type QueryTypes = string | DocumentQueryType;
// Given the query type, infer the doc type
type InferDocType<QueryType> = QueryType extends string ? string : never;
const useFirestore = <QueryType extends QueryTypes>(query: QueryType, doc?: InferDocType<QueryType>) => { }
// Valid Examples
useFirestore('posts', 'test');
useFirestore({ collection: "" });
// Valid Examples (may not want these?)
useFirestore('posts');
useFirestore({ collection: "" }, undefined);
// Invalid Examples
useFirestore({ collection: "" }, "test");
// Argument of type '"test"' is not assignable to parameter of type 'undefined'.(2345)
useFirestore('posts', null);
// Argument of type 'null' is not assignable to parameter of type 'string | undefined'.(2345)

Related

Types of property 'type' are incompatible. Problem with Typescript union types

Background
I am building a react site with some reusable generic UI components. Our backend service will return some responses with the data conforming to an abstract type.
For example
interface TypeAServerResponse {
somefield: string,
otherfield: string,
}
interface TypeBServerResponse {
somefield: string,
}
type TypeServerResponseUnion = TypeAServerResponse | TypeBServerResponse;
Both of the server response types contain somefield, and we would like to display that in the reused UI component. So we union them and tell the component to expect TypeServerResponseUnion.
However, in some occasions, we would also want to use otherfield, so we need to tell TypeScript to we are discriminating the union type. Without changing the backend to return a string literal, we are extending the ServerResponse types to contain a type string literal.
interface TypeA extends TypeAServerResponse{
$type: 'a',
}
interface TypeB extends TypeBServerResponse{
$type: 'b',
}
type TypeUnion = TypeA | TypeB; //or
type TypeUnion = TypeServerResponseUnion extends {
$type: 'a'|'b',
}
Now we can check on $type field in our UI component to discriminate the union and get otherfield when possible.
The problem
We now have some method to fetch the data from the server that returns TypeServerResponseUnion, and we want to parse it to TypeUnion before providing it to the UI layer.
// could be ajax.get, could be axios
const serverGet = () : TypeServerResponseUnion => {
return {somefield: 'something'}
}
const parse = () : TypeUnion => {
const response : TypeServerResponseUnion = serverGet();
// do something here to add the $item field and return it
}
We have two use cases
We know which concrete type we are asking for, so we can just provide the $type to the function. This has some problems I don't know how to deal with.
We don't know which concrete type we are asking for, we only know we are asking for a same type as we already have, this is the part where I am struggling with.
So I have the parse function as such:
const get = (original: TypeUnion) => {
const response = serverGet();
const parsedResponse: TypeUnion = {...response, $type: original.$type}
return parsedResponse
}
It complains with error:
Type '{ $type: "a" | "b"; somefield: string; otherfield: string; } | { $type: "a" | "b"; somefield: string; }' is not assignable to type 'TypeUnion'.
Type '{ $type: "a" | "b"; somefield: string; }' is not assignable to type 'TypeUnion'.
Type '{ $type: "a" | "b"; somefield: string; }' is not assignable to type 'TypeB'.
Types of property '$type' are incompatible.
Type '"a" | "b"' is not assignable to type '"b"'.
Type '"a"' is not assignable to type '"b"'.(2322)
So I want to know what is the best way to do typing for those types to solve this use case we are facing.
Extension
I also want to discuss this related problem with typescript.
If I change the get function to the following:
const get = (original: TypeUnion) => {
const response = serverGet();
const parsedResponse: TypeUnion = {} as TypeUnion;
parsedResponse.$type = original.$type
return parsedResponse
The error goes away, but of course because we are doing wrong type casting so it is not safe.
The question is why can we assign original.$type to TypeUnion.$type, where previously
const parsedResponse: TypeUnion = {...response, $type: original.$type}
we are assigning original.$type to $type during construction time does not work.
Playground with code
The reason for the type error is because you do not know if original and response are of the same type. Since they are both unions one could be of type "A" and the other of type "B". This might be be the true in the real implementation but it's not true in terms of the types.
We know which concrete type we are asking for, so we can just provide the $type to the function. This has some problems I don't know how to deal with.
This sorta seems like an anti pattern to me. If you know what type is coming from the backend then serverGet should not return a union but have the return type TypeAServerResponse or TypeBServerResponse
We don't know which concrete type we are asking for, we only know we are asking for a same type as we already have, this is the part where I am struggling with.
For this it is probably best to write a helper parse function (as you already did) but have but parse based on the data and not a value that is passed in.
const getPraseValueFromSErver: ()=>TypeUnion= () => {
const res = serverGet();
if("otherfield" in res){
// we know we have type A since otherfield exsists in the data
return { $itemType: "a", ...res}
} else {
// we know we have type B
return { $itemType: "b", ...res}
}
}
See full playground here

How to define structure of docs with interface

I have an interface describing the sctructure of my documents in a given collection:
interface IGameDoc {
playerTurn: string;
gameState: {
rowOne: [string, string, string]
rowTwo: [string, string, string]
rowThree: [string, string, string]
};
}
So if I fetch the docs in my collection
const gamesRef = useFirestore()
.collection('Games')
const { status, data } = useFirestoreCollectionData(gamesRef) //I would like data to be of type IGameDoc[]
Can this be achieved somehow?
You can define data to be of whatever type you want like below however you can't control what type is returned from the useFirestoreCollectionData service (in this piece of code).
You either need to transform it using a function.
The example below will cast it to a type and it will try to match as best as it can. It is hard for me to test without knowing more of your code.
const { status, data } : { status: any, data: IGameDoc[]} = useFirestoreCollectionData(gamesRef)

Pipe transform use reduce for array of object

this is my Interface file :
export interface ListCount {
centre?: string;
cause?: string;
totalTime?: number;
}
I am trying to make reduce to array of objects with pipe transform :
export class SumPipe implements PipeTransform {
transform(items: ListCount[], attr: string): number {
return items.reduce((a, b) => a + b[attr], 0);
}
}
and in compent HTML I looking to make sum of totalTime
{{ (delayCount$ | async) | sum:'totalTime'}}
But I have this error :
error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ListCount'.
Then I change the param attr: string to attr: keyof ListCount
and still have this error :
error TS2365: Operator '+' cannot be applied to types 'number' and 'string | number'.
and
error TS2532: Object is possibly 'undefined'.
Any help please
I would suggest the following:
restrict attr to point to numeric properties
take into account that properties can be optional. Use zero for those.
alternatively filter out missing (undefined) values.
export interface ListCount {
centre?: string;
cause?: string;
totalTime?: number;
otherTime?: number;
}
type NumericKeys<T> = {
[P in keyof T]: T[P] extends number ? P : never;
}[keyof T];
type NumericListCountKey = NumericKeys<Required<ListCount>>;
class SumPipe {
transform(items: ListCount[], attr: NumericListCountKey): number {
const elemes = items.map(elem => elem[attr]);
return elemes.reduce((prev: number, currentVal) => prev + (currentVal ? currentVal : 0), 0);
}
}
// alternatively, with filter
class SumPipe2 {
static isNumber(n: number | undefined): n is number {
return n != null;
}
transform(items: ListCount[], attr: NumericListCountKey): number {
const elems = items.map(elem => elem[attr])
.filter(SumPipe2.isNumber);
return elems.reduce((prev: number, currentVal) => prev + currentVal, 0);
}
}
Playground link
Ok, so your code compiles without issues and works. Here is a working stackblitz. If it fails on your local environment, perhaps try checking TS version, try restarting the Angular CLI, look for other issues or at least provided information on which line exactly the error is thrown.
There are a few issues with your code though.
As others have noted, passing any attr to the pipe and using the bracket notation to get the property value makes no sense. Only object accepted by the pipe is ListCount[], so it HAVE to be totalTime that gets summed as it's the only numeric property. It would make sense if you made more generic pipe that would accept any[] though.
Your pipe is not guarded for your use-case. totalTime is an optional property, meaning that if any item doesn't have totalTime defined (which it can, according to your interface) the pipe will return NaN. Not sure if that's the desired behavior.
According to this article, reduce() has an optional index, which points to the current index in the array. Knowing this, I'd opt for the following solution, leaving out attr entirely.
return items.reduce((a, b, index) => a + b[index].totalTime, 0);

How to define an object whose items can be accessed through a variable content in Typescript?

I'm new to typescript, trying to implement a content based on users browser language. Many different countries use the same language (with different locale keys) so i'm trying to filter them to avoid importing all locales from date-fns (which will be later on used).
const availableLanguages = {
es: 'es',
pt: 'pt-BR',
en: 'en-US'
}
const {i18n} = useTranslation(); // library for getting user locale
const browserLanguage = i18n.language.slice(0,2); // Handles pt-BR x pt-PT
const locale = availableLanguages[browserLanguage] // throws error
Last line throws
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ es: string; pt: string; en: string; }'.
No index signature with a parameter of type 'string' was found on type '{ es: string; pt: string; en: string; }'
error. How can I fix it?
Make sure the browserLanguage is one of the keys of the object first:
if (browserLanguage !== 'es' && browserLanguage !== 'pt' && browserLanguage !== 'en') {
// hopefully your app is designed so that this never occurs
// but having this branch will make TS happy
throw new Error('Language is not in availableLanguages');
}
const locale = availableLanguages[browserLanguage]
Other methods will require type assertions, eg:
if (!Object.keys(availableLanguages).includes(browserLanguage)) {
throw new Error('Language is not in availableLanguages');
}
const locale = availableLanguages[browserLanguage as keyof typeof availableLanguages];

Types for a function that receives an object of type `[key: string]: SOME_TYPE` and returns an array of type `SOME_TYPE[]`

I have some objects containing DB documents that I constantly need to convert to arrays.
Example:
const MY_OBJECT = {
docId_1: {...doc1},
docId_2: {...doc2},
docId_3: {...doc3},
// AND SO ON
}
I need to convert it to an array like this:
const MY_ARRAY_FROM_OBJECT = [
{...doc1},
{...doc2},
{...doc3},
// AND SO ON...
]
And this is code I use to do the conversion:
function buildArrayFromObject(obj) {
const keys = Object.keys(obj);
const arr = [];
for (const key of keys) {
arr.push(obj[key]);
}
return arr;
}
And I need to type that function so I can use it with objects that has types like these:
interface BLOGPOSTS_ALL {
[key: string]: BLOGPOST
}
interface PRODUCTS_ALL {
[key: string]: PRODUCT
}
So when I call them with each different object, I want Typescript to know what the return array type will be.
For example:
const BLOGPOSTS_ALL_ARRAY = buildArrayFromObject(BLOGPOSTS_ALL); // SHOULD BE "BLOGPOST[]"
const PRODUCTS_ALL_ARRAY = buildArrayFromObject(PRODUCTS_ALL); // SHOULD BE "PRODUCT[]"
Here is what I've tried:
function buildArrayFromObject<T, K extends keyof T>(obj: T): T[K][] {
const keys = Object.keys(obj);
const arr = [];
for (const key of keys) {
arr.push(obj[key]);
}
return arr;
}
But I'm getting this error:
And the returning type of the function is being evaluated by Typescript as type never[]
What you could do is the following:
Create an abstraction type to define what your database handles look like:
// Create an Entity type to define how your database objects look like
type Entities<T> = { [key: string]: T | undefined }
Therefore you can express your products and blogposts like this:
type BLOGPOSTS = Entities<BLOGPOST>;
type PRODUCTS = Entities<PRODUCT>;
In order to convert them in type-safe manner into an array you can use the Object.values method provided by the JavaScript API - for more information please see MDN
It's possible to replace the method buildArrayFromObject by something like this:
const isNil = <T>(a: T | null | undefined): a is null | undefined => a === null || a === undefined;
const isAssigned = <T>(a: T | null | undefined): a is T => !isNil(a);
const entitiesToArray = <T>(entity: Entities<T>): T[] => Object.values(entity).filter(isAssigned);
This method uses the Object.values method to convert the object into an array. Afterwards it get's filtered to contain an array without undefined values. Therefore I made use of two helper methods isAssigned and isNil. Please see this CodeSandbox for an example: Code SandBox
Based on your concern, that the Object.value method is not supported by IE11, you can add a polyfill for that one. Either by pasting a polyfill in or by adding it using npm to your project.
Alternatively you can replace this code by the following answer Use Object.keys to mimick Object.values

Resources