can ts object be strongly typed? 1

can ts object be strongly typed?

// This defines an interface that only allows values to be numbers
interface INumbersOnly {
  [key: string]: number;
}

// when using it, it will check that all properties are numbers
var x: INumbersOnly = {
  num: 1, // works fine
  str: 'x' // will give a type error
};

Here is what the above code is Doing:
1. We define an interface called INumbersOnly.
2. We define a property called key, which is a string.
3. We define the value of the property to be a number.
4. We define a variable called x, which is of type INumbersOnly.
5. We define a property called num, which is a number.
6. We define a property called str, which is a string.
7. We try to assign x to the object { num: 1, str: ‘x’ }.
8. The compiler will give us an error because str is not a number.

Similar Posts