How does one set a function's parameter type to accept a key of one of a type's properties? Is this even possible?
type A = {
['prop1']: string;
['props2']: boolean;
}
// arg would be either 'prop1' or 'prop2'
const example = (arg: property in A ) => {}
My assumption is that this is not even possible. If so, is there a way to get around this?
Is there a way to declare a type similar to how you can declare an object with an enum? Obviously, this is an object below, but could you do something similar with a type?
Example:
enum Enum {
bold = 'bold',
italic = 'italic',
}
const objWithEnumProperties: {[key in Enum]: any} = {
[Enum.bold]: '',
[Enum.italic]: ''
}
How to set a functions parameter type to be a property KEY of ONE of a types properties? Is this even possible?
Yes, using TypeScript keyof:
type Foo = { bar: string; baz: boolean; }
// arg is 'bar' | 'baz'
const fn = (arg: keyof Foo) => {}
Is there a way to declare a type similar to how you can declare a object with an enum?
You are probably wanting a const object assertion or an interface:
// Usable at runtime
const Foo = {
bar: 'bar',
baz: 'baz'
} as const;
// Only for typing
interface Foo {
bar: string;
baz: boolean;
}