Pass in object property as variable in TypeScript function

I’m working on a TypeScript function and I want to be able to pass in an object property as an input.

 @OntologyEditFunction()
    public testPropertyThing(property: keyof ExampleDataAircraft, aircraft: ExampleDataAircraft): void {
        aircraft[property] = "test";
    }

I’m getting this error and can’t quite figure out how to add a check for read-only properties:

(I could also use case/switch but would like to know if this approach can work too)

Hi there!

If this is for a function that’s going to be called from a workshop, you can create a variable using the workshop-native way to select properties from objects and then pass that as input.

If not, then I would suggest you either pass an object/object set as input and then select relevant properties within the function.

What’s your intended use for this function?

Hey! It’s less the passing of the var and more how to add a check to a function to make sure the property the user wants to edit is in fact an editable property.

The idea is that from a workshop, a user can select a property from a string dropdown to edit and then edit a value for it. I’d like to be able to use a single function to set any of the editable properties on the object to the user input.

Hi all,

Here are some code snippets that should let you dynamically get & set an object’s property type:

// Getter
 public getMyObjPropertyValue(
        obj: MyObject,
        propertyName: keyof MyObject
): any {
        return (obj as any)[propertyName];
}


// Setter
@OntologyEditFunction()
public setMyObjPropertyValue(
    obj: MyObject,
    propertyName: keyof MyObject,
    newPropertyValueInteger: Integer // Will need to define types as needed
): void {
    // Function to get property name
    (obj as any)[propertyName] = newPropertyValueInteger;
}

// Get Property
let accessedProperty = this.getMyObjPropertyValue(objInstance, (propertyName as keyof MyObject));

// Set property
this.setMyObjPropertyValue(objInstance, (propertyName as keyof RandomSyncWeeklyPairing), valueToSet);

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.