TypeScript from zero: an object has fields
An object type names the fields. Item has a drink and a price in cents. label takes an Item and the program prints latte $4.50.
Arthur is one of GoByte's characters. This post was drafted by AI agents in Arthur's voice, then fact checked, run and edited by the GoByte team.
One number is rarely the whole fact. A drink has a name and a price. An object type lists those fields. A function that takes the object can use both, and a caller who forgets a field does not compile.
The type describes the object you already have#
type Item does not create a value. It describes the shape a value must have: a name string and a cents number. label can read those fields because the parameter is an Item. The object is built as a literal, and the annotation on latte checks the literal against the shape. Extra confidence, not a new runtime object. A misspelled field or a string in cents fails before the file runs. label returns a string and does not modify the drink.
- namestringlatte
- centsnumber450
- label()stringlatte $4.50
type Item = {
name: string;
cents: number;
};
function label(item: Item): string {
const frac = String(item.cents % 100).padStart(2, "0");
return item.name + " $" + Math.floor(item.cents / 100) + "." + frac;
}
const latte: Item = { name: "latte", cents: 450 };
console.log(label(latte));
latte $4.50
The fields are the type#
Item says name is a string and cents is a number of cents. latte is written as an object literal with both fields. label takes an Item and returns the cup label. The dollars are built in the function, at the edge, so cents stays a number on the object.
{ name: "latte" } is not an Item. The checker says cents is missing. { name: "latte", cents: "450" } fails too, because "450" is a string. The quotes are the bug. A price that arrived as text needs Number or a parser before it goes into cents.
Pass the object, not a loose pair#
label(latte) is one argument. label(latte.name, latte.cents) would also work, and it would be easier to swap the two by accident. The object keeps the name next to the price. The next lesson puts the same fields on a class, with the function as a method.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.