Skip to main content

Interfaces

Interfaces are a way to describe properties and methods on an object. Unlike classes, they only exist at compile time: they're used for type checking, and are removed from the transpiled code.

Basic usage​

Interfaces can have both properties and methods.

interface Person
    name as string
    function getName() as string
end interface

sub test(bob as Person)
    print bob.name, bob.getName()
end sub
View the transpiled BrightScript code
sub test(bob as dynamic)
    print bob.name, bob.getName()
end sub

Use in functions​

Interfaces can be used as function parameter types and return types. These types will be converted into dynamic when the project is transpiled.

interface Dog
    name as string
    function walk()
end interface

sub walkThePuppy(puppy as Dog) as Dog
    puppy.walk()
    return puppy
end sub
View the transpiled BrightScript code
sub walkThePuppy(puppy as dynamic) as dynamic
    puppy.walk()
    return puppy
end sub

Namespaces​

Interfaces can also be defined inside namespaces

namespace humanoids
    interface Person
        name as string
        function getName() as string
    end interface
end namespace

sub test(bob as humanoids.Person)
    print bob.name, bob.getName()
end sub
View the transpiled BrightScript code
sub test(bob as dynamic)
    print bob.name, bob.getName()
end sub

Advanced types​

Interface member types can be defined as any valid BrighterScript type, and even reference themselves.

interface Dog
    owner as Human
end interface

interface Human
    pet as Dog
    mother as Human
end interface
View the transpiled BrightScript code

Methods​

Interfaces can describe complex methods as well

interface Dog
    sub barkAt(nemesis as Cat)
end interface
View the transpiled BrightScript code

Optional members​

Interfaces can include optional members. Optional members are denoted with the keyword optional before the name of fields, or before the function or sub keyword for methods. Interfaces with optional members will not incur a validation diagnostic if an object that is missing that member is passed to it, yet optional members will be included in completion results, and if referenced, they are inferred to be their declared type.

interface Video
    url as string
    length as float
    optional subtitleUrl as string
    optional rating as string
    optional genres as string[]
end interface
View the transpiled BrightScript code

Inline Interfaces​

Interfaces can be declared inline in any type expression. This provides a quick way to declare the members of an object without having to specify the name of the object or interface.

function getId(obj as {id as string}) as string
    return obj.id ' obj.id must exist, and it must be a string
end function
View the transpiled BrightScript code
function getId(obj as dynamic) as string
    return obj.id ' obj.id must exist, and it must be a string
end function