I want to limit the key of an object with interface.
I can achieve this by using type
type KeyOfObj = 'a' | 'b' | 'c';
type Type = { [key in KeyOfObj]?: string };
const objWithType: Type = {
a: 'a', // valid
b: 'b', // valid
c: 'c', // valid
d: 'd', // invalid
};
Is there a way to achieve the above behavior using interface?
In other words, is there a way to make code below valid?
type KeyOfObj = 'a' | 'b' | 'c';
interface Interface {
[key in KeyOfObj]?: string; // this code throws error
}
const objWithInterface: Interface = {
a: 'a', // valid
b: 'b', // valid
c: 'c', // valid
d: 'd', // invalid
};
I am still confused about when to use type vs interface for object even after reading this (https://medium.com/@martin_hotell/interface-vs-type-alias-in-typescript-2-7-2a8f1777af4c) article.
I always thought interface could do more than what type could do in terms of object. However, for the case above, it seems like type can do more compared to what interface can do. Any advice?
-- Question Summary --
How to make the second block of code valid while achieving what the first block of code is doing?
Any advice when to use
typevsinterfacedealing with object?
Thanks!