export type TodoQuery = {
sortBy?: 'createdAt' | undefined;
}
export const extractTodoQuery = (reqQuery: ParsedQs): TodoQuery => {
return {
sortBy: reqQuery.sortBy as 'createdAt' | undefined,
};
}
The reqQuery from extractTodoQuery function above comes from req.query in a node express app. I am trying to limit the sortBy property to certain string values or it should be undefined. Currently sortBy can still have different values in the return object based on the request query parameter. What would be an elegant way to achieve this in typescript?
You likely will want some kind of helper method to validate and return a strongly typed value. The cast doesn't force any conversion on its own and requires some validation logic.
There are many ways you could achieve this, but here is one approach by first defining an array of accepted values. Then, a helper that verifies sortBy is a string and is one of the values. If it's not a string or not one of the valid values, then it filters it out and returns undefined.
interface ParsedQs { [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[] }
// Valid sorting options. Change this as you please.
// The `as const` assertion ensures only these values are valid (not any `string`).
const SORT_BY = ['createdAt', 'updatedAt', 'name'] as const;
export type TodoQuery = {
// Infer the type based on the array so as you add/remove values the
// types automatically update.
sortBy?: typeof SORT_BY[number] | undefined;
}
// Helper to do the actual validation and return a strongly typed value.
const parseSortBy = (res: ParsedQs) => {
if (typeof res.sortBy === "string") {
return SORT_BY.find(valid => valid === res.sortBy)
}
return undefined;
}
export const extractTodoQuery = (reqQuery: ParsedQs): TodoQuery => {
return {
sortBy: parseSortBy(reqQuery),
};
}
TypeScript playground link.
I have been working on typescript for the last 4 months only, I am a kinda newbie, and need help.
Here is the type definition I am going to use as inferred type.
export type InputFileId = {
fileId: string;
rate?: 'satisfied' | 'investigation' | 'wrong' | 'none';
};
export type UserData= {
uId: string;
};
export type UpdateResponseObject = {
calculationName?: string;
temperatureC?: number,
isLoadChange?: boolean,
loadN?: number;
projectId?: string;
ownersIds?: Array<UserData>;
fileId?: Array<InputFileId>;
};
Here is what I want to achieve.
const responseData: UpdateResponseObject[] = [];
Now I want to use it as follows
let fileIdArray: any[] = [];
I want to send a response of type UpdateResponseObject and to do so I want to populate the keys/data as defined in the type definition.
responseData.fileId = fileIdArray;
Maybe edit the question or change it or maybe I am stupid.
I'm trying to construct a TS wrapper for localStorage with a TS schema that defines all the possible values in localStorage. Problem is that I can't figure out how to type the return value so that it's mapped to the approriate type from the schema: for example if I want to call LocalStorage.get("some_number"), I want the return type to be of type number. Is this even possible in TS?
Keys -typed parameter value works really well for the input!
type Values = LocalStorageSchema[Keys] returns the union type of the values which is not what I'm looking for.
Also it seems that it's not possible to use the variable key in the get function for type narrowing...
I have also looked into generic types: LocalStorage.get(...) but I think that kind of defeats the whole point of typing the return value.
Anyone got ideas for this? Thanks!
type LocalStorageSchema = {
token: string;
some_string: string;
some_number: number;
};
type Keys = keyof LocalStorageSchema;
// type Values = LocalStorageSchema[Keys]; ???
export const LocalStorage = {
get(key: Keys): any {
const data = window.localStorage.getItem(key);
//type ReturnType = ???
if (data !== null) {
return data;
}
console.error(`localStorage missing object with key ${key}`);
return null;
},
set(key: Keys, value: any) {
window.localStorage.setItem(key, value);
},
remove(key: Keys) {
window.localStorage.removeItem(key);
},
clear() {
window.localStorage.clear();
},
};
Use generics to return the right type for the key !
type LocalStorageSchema = {
token: string;
some_string: string;
some_number: number;
};
type Keys = keyof LocalStorageSchema;
export const LocalStorage = {
get<T extends Keys>(key: T): LocalStorageSchema[T] | null { // Return type will depend on the key
const data = window.localStorage.getItem(key);
//type ReturnType = ???
if (data !== null) {
return data as LocalStorageSchema[T];
}
console.error(`localStorage missing object with key ${key}`);
return null;
},
set<T extends Keys>(key: T, value: LocalStorageSchema[T]) {
window.localStorage.setItem(key, value as any);
},
remove(key: Keys) {
window.localStorage.removeItem(key);
},
clear() {
window.localStorage.clear();
},
};
const a = LocalStorage.get('token'); // string | null
Playground
You can use generic as in this link. There are still some errors left to fix. Link how to handle null values. It's up to you, so I didn't fix it.
I'm trying to narrow and type guard a property of an specific object while filtering and mapping but I'm not fully understanding how to do it.
Let's say I got the following array of Objects of interface Person:
interface IPerson {
name: string;
age: number;
height: number | null;
}
const personArray: IPerson[] = [...]
Let's say I would like to filter those that aren't null first and then map the result and do something with those filtered out.
personArray
.filter((person) => person.height !== null)
.map((person) => this.doSomethingAboutIt(person.height))
The doSomethingAboutIt function expects a number only, not a null. That's why I wanted to filter non-null first. But TypeScripts shows an error saying that doSomethingAboutIt is expecting a number, and not a number | null. Even thought there shouldn't be any null during the map function. Of course TypeScript doesn't know this yet. I thought it would be automatically inferred but I was wrong.
How can I narrow down the type to only number on object properties?
Thanks.
You need to use type guard as follows:
interface IPerson {
name: string;
age: number;
height: number | null;
}
const doSomethingAboutIt = (h: number) => {};
const personArray: IPerson[] = [];
personArray
.filter((person): person is IPerson & { height: number } => person.height !== null)
.map((person) => doSomethingAboutIt(person.height));
Code is:
const foo = (foo: string) => {
const result = []
result.push(foo)
}
I get the following TS error:
[ts] Argument of type 'string' is not assignable to parameter of type 'never'.
What am I doing wrong? Is this a bug?
All you have to do is define your result as a string array, like the following:
const result : string[] = [];
Without defining the array type, it by default will be never. So when you tried to add a string to it, it was a type mismatch, and so it threw the error you saw.
Another way is:
const result: any[] = [];
This seems to be some strange behavior in typescript that they are stuck with for legacy reasons. If you have the code:
const result = []
Usually it would be treated as if you wrote:
const result:any[] = []
however, if you have both noImplicitAny FALSE, AND strictNullChecks TRUE in your tsconfig, it is treated as:
const result:never[] = []
This behavior defies all logic, IMHO. Turning on null checks changes the entry types of an array?? And then turning on noImplicitAny actually restores the use of any without any warnings??
When you truly have an array of any, you shouldn't need to indicate it with extra code.
I got the same error in React function component, using useState hook.
The solution was to declare the type of useState at initialisation using angle brackets:
// Example: type of useState is an array of string
const [items , setItems] = useState<string[]>([]);
I was having same error In ReactJS statless function while using ReactJs Hook
useState.
I wanted to set state of an object array , so if I use the following way
const [items , setItems] = useState([]);
and update the state like this:
const item = { id : new Date().getTime() , text : 'New Text' };
setItems([ item , ...items ]);
I was getting error:
Argument of type '{ id: number; text: any }' is not assignable to parameter of type 'never'
but if do it like this,
const [items , setItems] = useState([{}]);
Error is gone but there is an item at 0 index which don't have any data(don't want that).
so the solution I found is:
const [items , setItems] = useState([] as any);
const foo = (foo: string) => {
const result: string[] = []
result.push(foo)
}
You needed specify what the array is since result = [] has a return type of any[]. Typically you want to avoid any types since they are meant to be used as an "Escape hatch" according to Microsoft.
The result is an object that is an array of string.
The solution i found was
const [files, setFiles] = useState([] as any);
I was able to get past this by using the Array keyword instead of empty brackets:
const enhancers: Array<any> = [];
Use:
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension())
}
Error: Argument of type 'any' is not assignable to parameter of type 'never'.
In tsconfig.json -
"noImplicitReturns": false,
"strictNullChecks":false,
Solution: type as 'never'
Remove "strictNullChecks": true from "compilerOptions" or set it to false in the tsconfig.json file of your Ng app. These errors will go away like anything and your app would compile successfully.
Disclaimer: This is just a workaround. This error appears only when the null checks are not handled properly which in any case is not a good way to get things done.
I got the error when defining (initialising) an array as follows:
let mainMenu: menuObjectInterface[] | [] = [];
The code I got the problem in:
let mainMenu: menuObjectInterface[] | [] = [];
dbresult.rows.forEach((m) => {
if (!mainMenu.find((e) => e.menucode === m.menucode)) {
// Not found in mainMenu, yet
mainMenu.push({menucode: m.menucode, menudescription: m.menudescription}) // Here the error
}
})
The error was: TS2322: Type 'any' is not assignable to type 'never'
The reason was that the array was initialised with also the option of an empty array.
Typescript saw a push to a type which also can be empty. Hence the error.
Changing the line to this fixed the error:
let mainMenu: menuObjectInterface[] = [];
You need to type result to an array of string const result: string[] = [];.
One more reason for the error.
if you are exporting after wrapping component with connect()() then props may give typescript errorSolution: I didn't explore much as I had the option of replacing connect function with useSelector hook
for example
/* Comp.tsx */
interface IComp {
a: number
}
const Comp = ({a}:IComp) => <div>{a}</div>
/* **
below line is culprit, you are exporting default the return
value of Connect and there is no types added to that return
value of that connect()(Comp)
** */
export default connect()(Comp)
--
/* App.tsx */
const App = () => {
/** below line gives same error
[ts] Argument of type 'number' is not assignable to
parameter of type 'never' */
return <Comp a={3} />
}
you could also add as string[]
const foo = (foo: string) => {
const result = []
(result as string[]).push(foo)
}
I did it when it was part of an object
let complexObj = {
arrData : [],
anotherKey: anotherValue
...
}
(arrData as string[]).push('text')
in latest versions of angular, you have to define the type of the variables:
if it is a string, you must do like that:
public message : string ="";
if it is a number:
public n : number=0;
if a table of string:
public tab: string[] = [];
if a table of number:
public tab: number[]=[];
if a mixed table:
public tab: any[] = [];
.......etc (for other type of variables)
if you don't define type of variable: by default the type is never
NB: in your case, you must know the type of variables that your table must contain, and choose the right option (like option 3 ,4 5 ).
This error occurs when you set the value of a property in an object when you haven't set the properties of the object. Declare a type for the object with its properties, then assign the type when you instantiated the object. Now you can set the values of the properties without this error.
I had this error for useRef
before with error:
const revealRefs = useRef([]);
const addToRefs = (el) => {
if (el && !revealRefs.current.includes(el)) {
revealRefs.current.push(el);
}
};
after without error:
const revealRefs = useRef<HTMLElement[]>([]);
const addToRefs = (el: HTMLElement | null) => {
if (el && !revealRefs.current.includes(el)) {
revealRefs.current.push(el);
}
};