Set init type / whole contract type

The following questions has been asked on Telegram:

There is no indication in the documentation regards to defining types in init (like self.init_type()…)
How does that work now with new syntax? Do you need it, can you do it, how can you do it?

Type inference usually figures out types from usage. However, for optional or complex types, you might want to specify them clearly.

The sp.cast instruction is now the primary way to define types explicitly.

Setting the whole storage type: By using sp.cast on self.data, you can set the type for the entire storage. For example:

@sp.module
def main():
    class MyContract(sp.Contract):
        def __init__(self):
            self.data.x = None
            self.data.y = "Test"
            sp.cast(self.data, sp.record(x=sp.option[sp.nat], y=sp.string))

Specifying type for specific fields: If you want to define the type for only a specific field, you can do so as follows:

self.data.x = sp.cast(None, sp.option[sp.nat])

You can choose to specify types for all storage or just parts. Clear types make contracts easier to understand.

2 Likes

How would you specify types and initialize an empty map where key is address and value is nat?

See Initializing (empty) map with record as value in a contract