Home > Back-end >  Setting a type for an object property using dot notation, only refers to a type, but is being used a
Setting a type for an object property using dot notation, only refers to a type, but is being used a

Time:10-14

I'm new to typescript, trying to define and assign an "Item" type to an object that's a child of another object.

This works:

interface Item {
    name: string
}
var bar: Item = {
    name: 'name',
};

This errors:

interface foo {}
var foo:foo = {};
interface foo {
    bar?: {}
}
interface Item {
    name: string
}
foo.bar:Item = {
    name: 'name',
}

Why?

'Item' only refers to a type, but is being used as a value here.

How can I assign a type to foo.bar?

Edit:

Based on heyitsjhu's answer,

interface foo {}
var foo:foo = {};
interface foo {
    bar?: {}
}
interface Item {
    name: string
}
foo.bar = {
    name: 'name',
} as Item

This works as expected, is there a way to put the "as Item" part next to the foo.bar = for readability? Or am I stuck with setting the type at the very end?

CodePudding user response:

Are you trying to say foo.bar is an Item? I think you can cast it as such:

interface Item {
  name: string
}

foo.bar = {
    name: 'name',
} as Item

If not, then you might want to assign foo an actual interface or type that defines what bar is expected to be.

interface Item {
    name: string
}

interface Foo {
    bar: Item
}

let foo: Foo = {
    bar: {
       name: 'name'
    }
}

CodePudding user response:

The type for the bar prop would need to be defined within the type definition for foo (Foo).

So:

type Foo: {
  bar: Item;
}

const foo: Foo = {
  bar: {
    name: "his name"
  }
}
  • Related