#Can a method be limited to only values in a lookup object?

13 messages · Page 1 of 1 (latest)

final mesa
#

I've got an like this

export const ids = {
  foo: 'this-is-foo',
  bar: 'this-is-bar',
}

Is there any way for me to define a function that only accepts 'this-is-foo' or 'this-is-bar' as parameters (or any other value stored in the lookup object).

I've tried this but it only accepts foo or bar. And while that's a good restriction for the IDE, my intent is to call the method like so someMethod(ids.foo) and not someMethod('foo') .

/** @param {keyof ids} id */
const someMethod(id) {...}

Is there any way to do this via typescript?

kind blaze
#

yes, pretty easy

#

you start with the object

export const ids = {
    foo: "this-is-foo",
    bar: "this-is-bar",
} as const;
#

you then take it's type

typeof ids
#

and you access it's values using indexed access

#

!hb indexed access

weary skiffBOT
kind blaze
#
type IDs = (typeof ids)[keyof typeof ids];
#

putting it all together

export const ids = {
    foo: "this-is-foo",
    bar: "this-is-bar",
} as const;

type IDs = (typeof ids)[keyof typeof ids];
//   ^?

function f(value: IDs) {}

f("this-is-bar");
f("this-is-foo");
f("some other key");
#

!ts

weary skiffBOT
#
export const ids = {
    foo: "this-is-foo",
    bar: "this-is-bar",
} as const;

type IDs = (typeof ids)[keyof typeof ids];
//   ^? - type IDs = "this-is-foo" | "this-is-bar"

function f(value: IDs) {}

f("this-is-bar");
f("this-is-foo");
f("some other key");
//^^^^^^^^^^^^^^^^
// Argument of type '"some other key"' is not assignable to parameter of type 'IDs'.
kind blaze
#

@final mesa

final mesa