4
I’m trying to declare a guy who accepts different properties with a number, for example: prop1
, prop2
... propN
. The point is, I’m having a hard time getting it to behave the way I expected it to, and I don’t understand why.
The code below has been tested in version 4.3.5 of Typescript:
type Props = {
[K in `prop${number}`]: boolean;
};
const myString = 'a';
const myNumber = 32;
const obj: Props = {
prop15: true,
propA: false,
[`prop${myNumber}`]: true,
[`prop${myString}`]: false,
anything: 137,
}
const obj2: Props = {};
const someNumber: Props = 32;
See on Playground.
But it seems that type
is not serving any purpose. None of the above code statements gave error. Even, when I put the cursor over Props
, appears type Props = {}
.
- What’s wrong with this guy, who’s taking anything?
- Is there any way to do what I need? Create a type that allows
prop1
,prop2
...propN
and nothing more?
But what the use-case for that? It doesn’t make much sense to type an object where several of the infinite possible properties wouldn’t exist. In that case, there’s no point in using a
unknown
?– Luiz Felipe
Anyway, the fact that no error is reported when trying to use an infinite set of key generator for an object seems to me a compiler bug. I know it’s not the same, but look at the error that’s being issued in this case.
– Luiz Felipe
use-case: I’m using express-Validator validation with wildcards, something like
'addresses.*.postalCode'
that would return me an object of erroraddresses[posição].postalCode
. It doesn’t sound like a good name for property, but for now I’ve been leaving it that way and I was trying to create a type for it, when I came across the problem described in the question. It seems to me that Typescript 4.4 has something that maybe I could fix it, but I couldn’t use it properly.– Rafael Tavares