Omit and Record
- TypeScript course
- Intermediate
- Lesson 26/89
- 4 min
Learn Omit for removing and Record for mapping.
Omit and Record
Omit<T, K> removes from T the properties listed in K and keeps the rest. Record<K, V> builds an object type that stores a V value for every K key. Together they are handy for narrowing an interface and storing the result in a key-value table.
interface Urun { ad: string; fiyat: number; }
type Adetli = Omit<Urun, "fiyat">;
type Stok = Record<string, number>;Mapping with Record
Record<K, V> is an object type where each key holds a value of the same type V. For example Record<string, number> maps city names to populations. For a fixed key set you can also use a union of keys like Record<"a" | "b", number>.
Practice Stock table
Define type Stok as Record<string, number>. Assign the object { elma: 5, armut: 3 } to a variable stoklar (of type Stok). Print stoklar.elma with console.log.
Starter code
// Stok türünü her string anahtar number değer tutacak şekilde tanımla
// stoklar değişkenine { elma: 5, armut: 3 } ata, türü Stok olsun
// stoklar.elma'yı console.log ile yazdırSample solution
type Stok = Record<string, number>;
const stoklar: Stok = { elma: 5, armut: 3 };
console.log(stoklar.elma);Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>Omit<Urun, "fiyat"></code> produce?
interface Urun { ad: string; fiyat: number; }
type T = Omit<Urun, "fiyat">;- A type with all properties optional
- A type with all properties required
- A type with fiyat removed and the rest kept Correct answer
- A type with only the fiyat property
Explanation: Omit removes the named properties and keeps the rest. Keeping only one is Pick, making optional is Partial, making required is Required.
2 Mapping type with Record
type Stok = ____<string, number>;
type Stok = Record<string, number>;
Explanation: For a key-to-value mapping you use Record. Partial, Pick and Required serve other purposes and do not produce a mapping type.
3 Omit and Record parts
| Term | Meaning |
|---|---|
Omit<T, K> |
Removes properties in K |
Omit<Urun, "fiyat"> |
Type with fiyat removed |
Record<K, V> |
Key-to-value mapping |
Record<string, number> |
Each string key maps to a number |