Is it possible to do a type annotation for a specific property when initialising an object in Typescript?
In my case I have a template literal type
type ID = `book#${string}`;
and I want to make sure that when I create an object (which needs to be of type Record<string, any>, so I cannot enforce type there):
const a = {
id: `book#abc` # Should be fine
}
that there is a lint / compile time error if I write for example
const a = {
id: `car#abc` # Should NOT be fine
}
I am looking for something along the lines of
const a = {
id: `book#abc` as ID
}
but that would just assume (assert?) that the id is correct.
The only solution I have found is to create a function
function asId(x: ID): ID {
return x;
}
which I don't find very nice.