Home > Net >  How to fix types parameters in typescript function?
How to fix types parameters in typescript function?

Time:12-28

There is a function:

function getFirstObjectArray<T>(obj: T): any | null {
    const keys = Object.keys(obj);
    
    if(keys.length) {
        const [key, ...restk] = keys;
        const [firstObject, ...restv] = obj[key] || [];
        return firstObject;
    }

    return null;
}

I have income object:

let obj = {100: [1, 2, 3], 200: [4, 5, 6]}  

As result I try to get 1. The first element of value the first object.

I get this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'.
  No index signature with a parameter of type 'string' was found on type 'unknown'.

So, I try to get first object then to get first element from array.

CodePudding user response:

I think this is what you're after:

interface MyInterface {
    [key: string]: number[] | any
}

function getFirstArrayMember(obj: MyInterface): number
function getFirstArrayMember(obj: any): null 
function getFirstArrayMember(obj: MyInterface | any): null | number {
    let result: number | null = null;
    Object.values(obj).map(val => {
        if (result === null && Array.isArray(val)) result = val[0]
    })
    return result
}

let obj = {100: [1, 2, 3], 200: [4, 5, 6]} 
let one = getFirstArrayMember(obj) // number

This will return the first element of the first array in the object, preserving type-safety. Returns null if the object has no array keys. Uses an overload so you don't have to check the union return type for compile-time values.

Playground

CodePudding user response:

If you don't use T in the other arguments or in the return value of your function then you don't need generics at all. Also, If your input object has an array of numbers as every value, just type it as is:

function getFirstObjectArray(obj: { [key: PropertyKey]: number[] }): any | null {
    const keys = Object.keys(obj);

    if (keys.length) {
        const [key, ...restk] = keys;
        const [firstObject, ...restv] = obj[key] || [];
        return firstObject;
    }

    return null;
}

TypeScript playground

CodePudding user response:

try

<T extends Record<string, number[]>>
  • Related