#Make generic optional by-default and required otherwise

1 messages · Page 1 of 1 (latest)

rough crypt
#

I'm making a class and I'd like to add an option to define the type/shape of custom data that later would be passed into functions.
How do I define a generic that by default should be empty/nothing/optional, but if it's assigned non-void type, then it should be required?

crimson sunBOT
#
rinart73#0

Preview:```ts
interface BarOptions<Data = void> {
count: number
data: Data
}

class Foo<Data = void> {
bar(options: BarOptions<Data>) {}
}

const one = new Foo<string>()
one.bar({count: 10, data: "hello"})

const two = new Foo()
two.bar({count: 10}) // shouldn't error```

rough crypt
#

Make generic optional by-default and required otherwise

past oyster
#

something like this?

crimson sunBOT
#
that_guy977#0

Preview:```ts
type BarOptions<Data> = {
count: number
} & ([Data] extends [never] ? {} : {data: Data})

class Foo<Data = never> {
bar(options: BarOptions<Data>) {}
}

const one = new Foo<string>()
one.bar({count: 10, data: "hello"})

const two = new Foo()
...```

rough crypt
#

Seems to work great, thank you. How do I "move" the data now when it's uncertain if it exists?