#Infer the types from an object

25 messages · Page 1 of 1 (latest)

proper bridgeBOT
#

@last dragon Here's a shortened URL of your playground link! You can remove the full link from your message.

bmkotu#7304

Preview:```ts
interface Simple {
[key: string]: string | Simple[]
}

interface ItemString {
value: string
name: string
}

interface ItemArray {
value: ItemString[]
name: string
}

interface Complex {
[key: string]: ItemString | Complex[]
}

const infer = (data: Simple): Compl
...```

proper bridgeBOT
#
Burrito#6903

Preview:```ts
type Infer<T> = {
-readonly [K in keyof T]: T[K] extends string
? {name: K; value: string}
: Infer<T[K]>
}

declare const infer: <T>(data: T) => Infer<T>

const data = {
name: "John",
age: "30",
pets: [
{
name: "Fido",
age: "10",
...```

proper bridgeBOT
#

@last dragon Here's a shortened URL of your playground link! You can remove the full link from your message.

Niek#4887

Preview:```ts
interface Simple {
[key: string]: string | Simple[]
}

interface ItemString {
value: string
name: string
}

interface Complex {
[key: string]: ItemString | Complex[]
}

type ArrayElement<Array> =
Array extends (infer Element)[] ? Element : never
...```

last dragon
#

It still contains some errors, but the idea is there

#

Also see this documentation page:

#

Ideally it should be recursive but one layer is fine too

dire shard
last dragon
#

thanks I will have a look at the code you posted

#

The type mapping I provided is recursive as well, yes. It doesn't support multiple different interfaces though. As long as it is just one class/interface, it should be fine

#

I see so the trick is to use the [key in keyof T] and use the ternary to check for the type it extends on inside the.. type

#

Exactly. This leaves the defined keys intact in the complex variant, and allows you to (recursively) map the strings to the complex strings and the simple arrays to complex arrays

#
proper bridgeBOT
#

@last dragon Here's a shortened URL of your playground link! You can remove the full link from your message.

bmkotu#7304

Preview:```ts
interface ISimple {
[key: string]:
| string
| ISimple[]
| (string | ISimple[])[]
}

interface IComplexValue {
value: string
name: string
}

type IComplex<T extends ISimple> = {
[K in keyof T]: T[K] extends string
? IComplexValue
: T[K] extends ISimple
...```

last dragon
#

With a bit of trickery to make sure mapping over the array works as well

#

now I want to the
interface ISimple {
[key: string]: string

not to just be a string but instead a "BaseType" like:
type BaseType = string | number | boolean | null | undefined;

#

but will this work in the ternary check?

#

It should yeah

#

Small word of warning though: I see you use infer as a variable name. This is technically allowed, but it is also a reserved word for use inside types

#

I try to avoid them in code

#

right yes thanks, it was just for the example 👍

#

Np. Good luck 🙂

#