Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. JavaScript
    5. Typescript setObejct kompelier fehler

    NEWS

    • Neuer Blog: Fotos und Eindrücke aus Solingen

    • ioBroker@Smart Living Forum Solingen, 14.06. - Agenda added

    • ioBroker goes Matter ... Matter Adapter in Stable

    Typescript setObejct kompelier fehler

    This topic has been deleted. Only users with topic management privileges can see it.
    • I
      ignis-draco last edited by ignis-draco

      Hi,

      ich komme an einer stelle mit meinem Typescipt Skript nicht weiter.
      Ich möchte gerne "states" erstellen bei dem es im "Wert" eine Auswahl gibt.
      Screenshot 2024-02-29 090448.png
      Für die Auswahl habe ich ein Emun erstellt.

      enum LightMode{
          MANUALL, 
          PRESSEND,
          ASTRO,
          TIME,
          TIME_PRESSEND,
          ASTRO_PRESSEND
      }
      

      aus diesem Enum baue ich dann ein Object

      {
            "0": "MANUALL",
            "1": "PRESSEND",
            "2": "ASTRO",
            "3": "TIME",
            "4": "TIME_PRESSEND",
            "5": "ASTRO_PRESSEND",
          }
      

      das ich beim erstellen des States mitgebe

      createStateAsync(testPath,{name: "test1", type: 'number', states:{"0":"MANUALL", .....}}
      

      Bis hierhin geht auch alles. Jetzt möchte ich noch die Möglichkeit haben das, wenn sich das enum mal ändert (z.b. ein weiterer Eintrag) dieses auch im Object angepasst wird.
      Mit

      extendObject(testPath, {common:{states:{"0":"MANUALL", .....}}})
      

      ist es möglich, dies zu ändern, wenn ein neuer Eintrag hinzukommt jedoch nicht, wenn ich einen Eintrag entferne.
      Ich habe es dann noch mit

      const obj= getObject(testPath)
      obj.common.states = {"0":"MANUALL", .....}
      setObject(testPath, obj, (err) => {
                  if (err) log('Cannot write object: ' + err);
              });
      

      versucht was leider zu fehlern beim Kompilierne führte.

      javascript.0 (435) script.js.common.dev: TypeScript compilation failed: setObject(testPath, obj, (err) => { ^ ERROR: Argument of type '{ type: "state" | "channel" | "folder" | "device"; ts: number; from: string; common: { [x: string]: any; [x: number]: any; }; acl: { object: number; state: number; owner: string; ownerGroup: string; }; ... 5 more ...; user: string; }' is not assignable to parameter of type '(Omit<StateObject, "acl" | "_id"> & { _id?: string; acl?: StateACL; }) | (Omit<InstanceObject, "acl" | "_id"> & { _id?: string; acl?: ObjectACL; }) | ... 10 more ... | (Omit<...> & { ...; })'. Type '{ type: "state" | "channel" | "folder" | "device"; ts: number; from: string; common: { [x: string]: any; [x: number]: any; }; acl: { object: number; state: number; owner: string; ownerGroup: string; }; ... 5 more ...; user: string; }' is not assignable to type 'Omit<StateObject, "acl" | "_id"> & { _id?: string; acl?: StateACL; }'. Type '{ type: "state" | "channel" | "folder" | "device"; ts: number; from: string; common: { [x: string]: any; [x: number]: any; }; acl: { object: number; state: number; owner: string; ownerGroup: string; }; ... 5 more ...; user: string; }' is not assignable to type 'Omit<StateObject, "acl" | "_id">'. Types of property 'type' are incompatible. Type '"state" | "channel" | "folder" | "device"' is not assignable to type '"state"'. Type '"channel"' is not assignable to type '"state"'. 
      


      Bei der Suche hier im Forum haben die diesen Eintrag gefunden
      https://forum.iobroker.net/topic/57264/gelöst-typescript-kompilierfehler-setobject/17
      darauf hin haben ich das auch versucht.

       const obj= getObject(testPath) as iobJS.StateObject;
       obj.common.states =   {"0":"MANUALL", .....}
       setObject(testPath, obj, (err) => {
                  if (err) log('Cannot write object: ' + err);
              });
          }
      

      leider war es auch nicht erfolgreich.

      javascript.0 (435) script.js.common.dev: TypeScript compilation failed: obj.common.states = lightModeStates(); ^ ERROR: Type 'object' is not assignable to type 'string | Record<string, string>'. 
      

      Kann mir jemand sagen wo mein Fehler ist oder einen Tipp geben über welchen weg ich das hinbekomme ?

      Ach ja mein Test state ist

      {
        "common": {
          "name": "test1",
          "type": "number",
          "states": {
            "0": "MANUALL",
            "1": "PRESSEND",
            "2": "ASTRO",
            "3": "TIME",
            "4": "TIME_PRESSEND",
            "5": "ASTRO_PRESSEND",
            "6": "MAX",
            "7": "__LENGTH"
          },
          "role": "state"
        },
        "native": {},
        "type": "state",
        "from": "system.adapter.javascript.0",
        "user": "system.user.admin",
        "ts": 1709191401013,
        "_id": "0_userdata.0.dev.intTest"
      }
      

      Und natürlich ist "setObject" im JS adapter erlaubt.

      gruß

      haus-automatisierung 1 Reply Last reply Reply Quote 0
      • haus-automatisierung
        haus-automatisierung Developer Most Active @ignis-draco last edited by haus-automatisierung

        hier stand Quatsch

        haus-automatisierung 1 Reply Last reply Reply Quote 0
        • haus-automatisierung
          haus-automatisierung Developer Most Active @haus-automatisierung last edited by

          Bei mir funktioniert das in 7.8.0 ohne Fehler:

          const obj= getObject('0_userdata.0.test') as iobJS.StateObject;
          obj.common.states = {'0': 'MANUALL'};
          
          setObject('0_userdata.0.test', obj, (err) => {
              if (err) log('Cannot write object: ' + err);
          });
          
          1 Reply Last reply Reply Quote 1
          • I
            ignis-draco last edited by ignis-draco

            @haus-automatisierung
            Danke mit den Hinweis habe ich meinen Fehler gefunden.

            Ich hatte über eine Funktion aus dem Enum die das zusammen gebaut.

            function lightModeStates(){
                let ret = ""
                for (var enumMember in LightMode) {
                    if (typeof(LightMode[enumMember]) === 'number'){
                        ret += ",\"" + LightMode[enumMember] + "\":\"" + enumMember + "\""
                    }
                }
                return   JSON.parse("{" + ret.substring(1) + "}")  // remove "," 
            }
            

            Und mein Fehler war das ich gedacht habe das dort ein Object auskommt somit hatte ich als Rückgabe Obejct eingetragen.
            Nachdem ich das entfernt habe geht alles. Manchmal sind es die kleinen Dinge.

            haus-automatisierung 1 Reply Last reply Reply Quote 0
            • haus-automatisierung
              haus-automatisierung Developer Most Active @ignis-draco last edited by haus-automatisierung

              @ignis-draco sagte in Typescript setObejct kompelier fehler:

              Ich hatte über eine Funktion aus dem Enum die das zusammen gebaut.

              Die Funktion ist ja ultra umständlich. Erst manuell JSON zusammenbauen, um es dann wieder zu parsen?! Nur damit es Strings werden, oder wie?

              const result = {};
              Object.keys(LightMode).forEach((key) => {
                  result[key] = typeof LightMode[key] !== 'string' ? String(LightMode[key]) : LightMode[key];
              });
              return result;
              
              1 Reply Last reply Reply Quote 0
              • I
                ignis-draco last edited by ignis-draco

                @haus-automatisierung

                Da hast du natürlich recht. Wobei ich den Quellcode von dir korrigieren muss.
                Ein Enum in Typstript ist immer doppelt (hin und Rückrichtung). Mit deinem Code wären alle Eintrag doppelt da.

                    const result = {};
                    Object.keys(LightMode).forEach((key) => {
                        if (!isNaN(parseInt(key))){
                            result[key] = String(LightMode[key])
                        }
                    });
                    return result;
                

                Damit Passt es jetzt.

                haus-automatisierung 1 Reply Last reply Reply Quote 0
                • haus-automatisierung
                  haus-automatisierung Developer Most Active @ignis-draco last edited by

                  @ignis-draco sagte in Typescript setObejct kompelier fehler:

                  Mit deinem Code wären alle Eintrag doppelt da.

                  Wie soll das gehen? Schlüssel sind eindeutig

                  1 Reply Last reply Reply Quote 0
                  • I
                    ignis-draco last edited by ignis-draco

                    @haus-automatisierung sagte in Typescript setObejct kompelier fehler:

                    Wie soll das gehen? Schlüssel sind eindeutig

                    Das hat mich auch sehr verwundert.
                    Wenn man den Code ausführt bekommt man:

                    { '0': 'MANUALL', 
                      '1': 'PRESSEND', 
                      '2': 'ASTRO', 
                      '3': 'TIME', 
                      '4': 'TIME_PRESSEND', 
                      '5': 'ASTRO_PRESSEND',  
                      MANUALL: '0', 
                      PRESSEND: '1', 
                      ASTRO: '2',
                      TIME: '3', 
                      TIME_PRESSEND: '4',
                      ASTRO_PRESSEND: '5' }
                    

                    Halt ein mal Hin und einmal Rück.

                    haus-automatisierung 1 Reply Last reply Reply Quote 0
                    • haus-automatisierung
                      haus-automatisierung Developer Most Active @ignis-draco last edited by

                      @ignis-draco sagte in Typescript setObejct kompelier fehler:

                      Halt ein mal Hin und einmal Rück.

                      Dafür ist dann aber nicht der Code verantwortlich, sondern das muss dann schon in LightMode genauso stehen.

                      1 Reply Last reply Reply Quote 0
                      • I
                        ignis-draco last edited by

                        @haus-automatisierung

                        Klar habe ja auch gesagt das es an der Enum Implementation von Typscript liegt.

                        @ignis-draco sagte in Typescript setObejct kompelier fehler:

                        Ein Enum in Typstript ist immer doppelt (hin und Rückrichtung). Mit deinem Code wären alle Eintrag doppelt da.

                        haus-automatisierung 1 Reply Last reply Reply Quote 0
                        • haus-automatisierung
                          haus-automatisierung Developer Most Active @ignis-draco last edited by haus-automatisierung

                          @ignis-draco sagte in Typescript setObejct kompelier fehler:

                          Ein Enum in Typstript ist immer doppelt (hin und Rückrichtung). Mit deinem Code wären alle Eintrag doppelt da.

                          Das ist am Ende ja ein ein normales Objekt. Da gibt es keinen "Hin- und Rückweg" welcher automatisch erstellt wird.

                          EDIT: Ach krass, gerade wirklich etwas neues gelernt (ich nutze Enum eigentlich nie, daher ist mir das bisher nicht aufgefallen)! Danke:

                          enum UserResponse {
                            No = 0,
                            Yes = 1,
                          };
                          
                          console.log(JSON.stringify(UserResponse));
                          
                          // {"0":"No","1":"Yes","No":0,"Yes":1}
                          
                          1 Reply Last reply Reply Quote 0
                          • I
                            ignis-draco last edited by

                            @haus-automatisierung

                            Das Zauberwort lautet Reverse mappings.
                            Willkommen im Club habe das auch erst heute gelernt.

                            1 Reply Last reply Reply Quote 1
                            • I
                              ignis-draco last edited by

                              Ich muss das Thema leider noch mal hochholen.

                              Meine Test Version funktioniert ja.

                              const testPath = "0_userdata.0.dev.color_mode"
                              const obj= getObject(testPath) as iobJS.StateObject;
                              

                              Als ich das ganze aber dynamisch machen wollte z.b.

                              async function updateEnum(path:string, states, statesLength){
                                  const obj= getObject(path) as iobJS.StateObject;
                              

                              hatte ich wieder den Fehler.

                              Wenn ich aus dem const ein var machen geht es auch nicht mehr

                                  var testPath = "0_userdata.0.dev.color_mode"
                                  const obj= getObject(testPath) as iobJS.StateObject;
                              

                              und es reicht nicht aus den string in ein const zu packen

                              async function updateEnum(path:string, states, statesLength){
                                  const testPath = path
                                  const obj= getObject(testPath) as iobJS.StateObject;
                              

                              immer bekommen ich

                              script.js.common.dev: TypeScript compilation failed: const obj = getObject(path) as iobJS.StateObject; ^ERROR: Conversion of type '{ type: "meta" | "config" | "user" | "state" | "instance" | "adapter" | "channel" | "folder" | "device" | "script" | "enum" | "group" | "host" | "chart"; ts: number; from: string; common: { ...; }; ... 8 more ...; encryptedNative: string[]; }' to type 'StateObject' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Types of property 'common' are incompatible. Type '{ [x: string]: any; [x: number]: any; }' is missing the following properties from type 'StateCommon': read, write, role, name
                              

                              Leider fehlt mir da echt tiefergehendes Javascript/typescript wissen um das zu verstehen.
                              Würde mir noch mal jemand auf die Sprünge helfen?

                              1 Reply Last reply Reply Quote 0
                              • First post
                                Last post

                              Support us

                              ioBroker
                              Community Adapters
                              Donate

                              872
                              Online

                              31.8k
                              Users

                              80.0k
                              Topics

                              1.3m
                              Posts

                              2
                              13
                              376
                              Loading More Posts
                              • Oldest to Newest
                              • Newest to Oldest
                              • Most Votes
                              Reply
                              • Reply as topic
                              Log in to reply
                              Community
                              Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
                              The ioBroker Community 2014-2023
                              logo