#How to define a constructor parameter type based on another parameter

9 messages · Page 1 of 1 (latest)

maiden grottoBOT
#
istedist#9580

Preview:```ts
interface Building {
floors: number
}

const building: Building = {floors: 6}

class Person {
constructor(
public building: Building,
public position: number // How to use TypeScript type annotation to
) //
...```

frosty shale
#

I want position to be an integer from 1 to this.building.floors.

tight plinth
#

You need to change how building is declared to preserve the type, and then use recursive type to create a union of all the allowed values.

#

Personally I would suggest against it.

frosty shale
tight plinth
#

I’m on mobile, I’ll reply later if someone else hasn’t got to it by then.

maiden grottoBOT
#
nonspicyburrito#0

Preview:```ts
interface Building {
floors: number
}

type OneTo<N extends number, R extends number[] = [never]> = R['length'] extends N
? R[number] | N
: OneTo<N, [...R, R['length']]>

class Person<T extends Building> {
constructor(building: T, position: OneTo<T['floors']>) {}
...```

tight plinth
#

Again, I would strongly recommend you to not do this.

#

The extra safety is not worth the cons in most cases.