Newly Written:
I have a function that retrieves an object from a database. I am looking to replace the type Record<string, unknown> with a generic.
interface GetObjectParams {
key: string
}
interface GetObject {
<T> (params: GetObjectParams): Promise<T | null>
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const getObjectFromDatabase = (params: GetObjectParams) => ({'text': 'Hello world'});
const getObject: GetObject = async <T> (
params
) => getObjectFromDatabase(params);
getObject<SOME TYPE>({key: 'some key'});
Revised Version:
interface GetObjectParams {
key: string
}
interface GetObject {
<T> (params: GetObjectParams): Promise<T | null>
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const getObjectFromDatabase = (params: GetObjectParams) => ({'text': 'Hello world'});
const getObject: GetObject = async <T> (
params: GetObjectParams
) => getObjectFromDatabase(params) as unknown as T;
getObject<SOME TYPE>({key: 'some key'});
In the revised version above, typescript throws an error stating that params has not been defined
Parameter 'params' implicitly has an 'any' type.
https://i.sstatic.net/emORO.png
Typescript stops complaining when I explicitly define what params is:
const getObject: GetObject = async <T> (
params: GetObjectParams
) => getObjectFromDatabase(params) as unknown as T;
Why is it necessary to declare params?