Create Type that consists of readonly properties from imported classes
given classes like the following
class Dog {
public readonly key:string = 'dog'
}
class Cat {
public readonly key:string = 'cat'
}
export default [new Dog(), new Cat()]
is it possible to import those into another file, treat them as a const, and derive a type from their key
?
import animals from '...'
type AnimalKeys = typeof animals[number]['key'] // type string
the type AnimalKeys
is string
. I'm hoping for the type to be 'dog' | 'cat'
playground
Solution 1:
Don't type them as a string.
class Dog {
public readonly key = 'dog' as const
}
class Cat {
public readonly key = 'cat' as const
}
const animals = [new Dog(), new Cat()]
type AnimalKeys = typeof animals[number]['key'] // type 'cat' | 'dog'
Playground