search

Home  >  Q&A  >  body text

typescript object literal type definition

I want to use typescript to define an object. The object can have any properties, but when accessing the properties, an error will be reported, showing Property "a" does not exist on type Object. Is there a way to define it? Such an object?

type Options = {
    data: Object
}
const v: Options = {
    data: {
        a: 1,
        b: 2
    }
}
v.data.a
// Property "a" does not exist on type Object
为情所困为情所困2698 days ago1100

reply all(2)I'll reply

  • 阿神

    阿神2017-07-05 11:09:22

    You defined data as Object, Object does not have a attribute

    If you want to define an object with a key:value structure, do this

    data: { [key: string]: any } 

    reply
    0
  • 天蓬老师

    天蓬老师2017-07-05 11:09:22

    Your data has no declared attributes and defaults to an empty object. Then you call a and it does not exist in the type declaration and an error is reported

    reply
    0
  • Cancelreply