#Decorators not being able to set field

19 messages · Page 1 of 1 (latest)

mint dagger
#

I want to be able to set a parameter on a class which is defined in a parent with a decorator. My code looks like this:

Decorator:

const meta = (target: typeof Service, field: string) => {
    if (!target.prototype.__meta__) {
        target.prototype.__meta__ = {}
    }
    if (!target.prototype.__meta__![field]) {
        target.prototype.__meta__![field] = ''
    }
}

export const Suffix = (baseSuffix: string = '') => {
    return (target: typeof Service) => {
        meta(target, 'suffix')
        target.prototype.__meta__!.suffix = baseSuffix
    }
}

Service class:

export class Service {
    public __meta__: any
}

Index:

@Suffix('hello world')
class TestService extends Service {}

const testService = new TestService()
console.log(testService) // prints TestService { __meta__: undefined }
wind drumBOT
#
Ascor8522#7606

Preview:```ts
const meta = (
target: typeof Service,
field: string
) => {
target.prototype.meta ??= {}
target.prototype.meta![field] ||= ""
}

const Suffix =
(baseSuffix = "") =>
(target: typeof Service) => {
meta(target, "suffix")
target.prototype.meta!.suffix = baseSuffix
...```

rough bolt
#

are you sure the code is printing TestService { __meta__: undefined } ?

#

it prints nothin in the playground

#

nevermind, had to open the browser's console

#

it's working as expected

#

@mint dagger

#

also, you probably should use any on the Service, especially if you know what kind of data you'll store in there (whether by using the decorator or not)

mint dagger
rough bolt
#

make sure you're running TypeScript <=4.9.5

#

since you're still using the old decorator syntax

mint dagger
#

what's the new syntax? also how can i check the version

rough bolt
#

how can i check the version
check your package.json

#

to see what version of TS you have

mint dagger
#

fixed by setting target in tsconfig to es2017