The following code just perfectly generates me a type that only allows existing hobbies:
const personWithHobby = [
{
name: "John",
age: 30,
hobby: "Football"
},
{
name: "Doe",
age: 24,
hobby: "Soccer"
}
] as const;
type Hobby = typeof personWithHobby[number]['hobby'];
let hobby: Hobby = 'Football';
//Does not work:
hobby = 'Tennis';
Now I need this type to be of the following type, too:
type Person = {
name: string;
age: number;
doSomething: (v: string) => string;
};
My first attempt does not work since TS wants me to remove hobby
:
const personWithHobby: Person[] = [
{
name: "John",
age: 30,
doSomething: v => v.length.toString(),
//ts(2353) only known properties
hobby: "Football"
}
] as const;
Removing the type does work, but now the parameter type of doSomething
can’t be resolved automatically:
const personWithHobby = [
{
name: "John",
age: 30,
//ts(7006) implicit any type
doSomething: v => v.length.toString(),
hobby: "Football"
}
] as const;
I know I could allow implicit any, but I want the type to be known. Is it somehow possible to achieve both? Implicitly creating a new type based on the current one? So I can (again implicitly) have a type Hobby?