There is no need to type-check {name: "test"} as const
because Typescript uses structural equality meaning aslong as {name: "test"} as const
is the same structure of MyType they will be equal and therefore the same.
This behaviour can be observed using these helper types.
interface MyType {
name: string;
}
const test = {name: "test"} as const;
type IsEqual<T, U> = [T] extends [U] ? true : false;
type AreTheyEqual = IsEqual<typeof test, MyType> // true they are the same.
Anything that takes a MyType can take a typeof Test.
EDIT: If you want to force test to be of type MyType to type-check test there you cannot do this by keeping the string literal because anything asserted to be MyType will lose the literal type and fall back to string this behaviour can be observed here.
type MyType = {name: string};
const x:MyType = {
name: 'test' as const
}
type Test = typeof x["name"] // string;
Meaning if you want to have both Literal and string types on MyType you will need to instead do something like this (changing MyType). Note using this seems verbose but is arguably less boilerplate than "as const"
interface MyType<NAME extends string = string> {
name: NAME;
}
const x: MyType = {
name: 'test' // string;
}
const y: MyType<"test"> = {
name: "test" // "test"
}
type Test1 = typeof x["name"]// string;
type Test = typeof y["name"] // "test";
^ Both string and literal types allowed.