2

I have a custom component that passes an object to the viewmodel of that component. Al this using typescript. The object arrives in the constructor but it is wrapped in an anonymous object by knockout.

Is there a way to prevent this and just get the strongly typed value object?

In the constructor I get this:

 Object { value: Order, $raw: Object }

I would like to have the value/Order immediately.

Here is my code:

index.html:

<div data-bind="foreach: Orders"/>
     <my-component params="value: $data"></my-component>
</div>

component.html:

 <span data-bind="text: Name"></span>

component.ts

ko.components.register('my-component', {
     viewModel: ComponentVm,
     template: component.html"
});

Component.ts:

class ComponentVm{
     public Name:string;

     constructor(order:Order){
          this.Name = order.Name; //Problem here because of anonymous object
     }
}

Order.ts:

Class Order {
      public Name:string = "Bob";
      constructor(){}
}

One solution would be:

 class ComponentVm{
     public Name:string;

     constructor(anonymousObject:any){
          let order = anonymousObject.value;
          this.Name = order.Name;
     }
}

But that is not really nice.

0

2 Answers 2

4

You can specify "params" object type in the "Component.ts":

class ComponentVm {
     public Name:string;

     constructor(params: { order: Order }){
          this.Name = params.order.Name;
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Pretty sure the short answer is "no". Components receive a params argument. But that doesn't mean you have to use an any type. Your params object should be well-defined.

params — an object that will be passed on to the component. Typically this is a key-value object containing multiple parameters, and is typically received by the component’s viewmodel constructor.

2 Comments

Sorry i'm afraid i don't follow. How can i define the params object if i have no control over it? It supposed to be an Order (which is the definition of the params).
No, it's an object that contains an Order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.