#Implicit type any

17 messages · Page 1 of 1 (latest)

eternal rapids
#

Could you please tell me how can I make the following code work, without explicit cast to any? ts function formatObj(input: object) { for(const key in input) { formatUnknown(input[key]); } } function formatUnknown(input: unknown) {}
Currently No index signature with a parameter of type 'string' was found on type is thrown. I could add an index signature to the parameter( { [x: string | number | symbol]: unknown } ), but in such case not every object will be applicable.

vale pagoda
#

you could have a type parameter K and use Record<K, unknown>

eternal rapids
#

If I put Record<string | symbol | number, unknown> as a type of input parameter, then calling formatObj with object type as an argument fails.

#

and writing formatUnknown((input as Record<string | symbol | number, unknown>)[key]) seems worse than as any

vale pagoda
#

why do you have something of type object at all

#

honestly this seems somewhat of a mistake to have

#

generally the object's own toString is better if such exists, or util.inspect is sufficient for node

eternal rapids
#

Type object was added by TypeScript internally, while narrowing down type unknown in the following code:

#
function formatUnknown(input: unknown) {
  if (input === undefined || input === null || typeof input === "boolean") {
    return String(input);
  } else if (typeof input === "number" || typeof input === "bigint" || typeof input === "string") {
    return input.toString(); //simplified code ofc
  } else {
    return formatObject(input);
  }
}```
#

When flag strictNullChecks is set to false, input is of type unknown while passing it to formatObject

#

but when scriptNullChecks is true, I still get Argument of type '{}' is not assignable to parameter of type 'Record '.

vale pagoda
#

oh yeah that's understandable

#

really though, why not just use tools that already exist?

eternal rapids
#

I am porting a simple tool from JS and I want to keep the original logic. Overall this format file is not large, like 150 lines of code

#

while importing a new library for the same purpose would likely require some tweaking to make outputs look as expected and probably size would be much bigger

vale pagoda
#

util.inspect is a built-in for node and it has browser ports

eternal rapids
#

I will take a look, thanks