Lably
Skip to content

Type safety

Extent to which a programming language discourages type errors

  • 17 min read
  • 8 chapters

Related on Lably

Through Computer science, Value (computer science) and Data type

Type enforcement can be static (catching potential errors at compile time), dynamic (associating type information with values at run-time and consulting them as needed to detect imminent errors), or a combination of both. Dynamic type enforcement can often run programs that would be invalid under static enforcement, but at the cost of introducing errors at runtime.

In the context of static (compile-time) type systems, type safety usually involves (among other things) a guarantee that the eventual value of any expression will be a legitimate member of that expression's static type. The precise requirement is more subtle than this — see, for example, subtyping and polymorphism for complications.

Definitions

British computer scientist Robin Milner states that:

Well-typed programs cannot "go wrong".

If a type system is sound, then expressions accepted by that type system must evaluate to a value of the appropriate type (rather than produce a value of some other, unrelated type or crash with a type error). AT&T researcher Vijay Saraswat provides the following, related definition:

A language is type-safe if the only operations that can be performed on data in the language are those sanctioned by the type of the data.

What it means for a program to be "well typed" or to "go wrong" are properties of its static and dynamic semantics, which are specific to each programming language. Consequently, a precise, formal definition of type soundness depends upon the style of formal semantics used to specify a language. Computer scientists Andrew K Wright and Matthias Felleisen formulate a definition and proof technique for type safety in languages defined by operational semantics. Under this approach, the semantics of a language must have the following two properties to be considered type-sound:

Progress
A well-typed program never gets stuck. Every expression is either already a value or can be reduced towards a value in some well-defined way.
Preservation (or subject reduction)
After each evaluation step, the type of each expression remains the same (that is, its type is preserved).

A number of other formal treatments of type soundness have also been published in terms of denotational semantics and structural operational semantics.

Sign in to keep reading

7 more chapters are free with a Lably account.

More in Computing and communication