0

Not sure if this is possible but I'd like to write a function where I take in a string and an object.

The type of the second object should contain a property with a name that is the same as the before mentioned string and have a certain type.

E.g.

// No error
someFuncion("foo", {foo: 42})

// Error
someFuncion("foo", {foo: "a string instead of a number"})
someFuncion("foo", {bar: 42})

Can anyone show me what the type signature for this function would be please?

Thanks

2 Answers 2

2

I think what you are looking for is a generic function with a default generic type.

function someFunction<T extends string>(param1: T, param2: Record<T, number>) {}

Link to playground

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome that is exactly what I was looking for. Out of curiosity, can you explain the string = string bit? I come from a C# background so restricting a generic param to a certain type makes sense so I understand T extends string but it's the following equals that throws me a bit.
i just realized that it is not at all necessary in this function type. its basically a default value if no type is provided. typescriptlang.org/docs/handbook/release-notes/…
0

You can achieve that very easily using interfaces.

The function must accept a string and an object.

Using Typescript interfaces (suggested):

The parameters of obj must follow the interface IObject.

interface IObject {
  foo: number;
};

function someFunction(str: string, obj: IObject): void {
  // ...
}

Without interface declaration "inline":

function someFunction(str: string, obj: { foo: number }): void {
  // ...
}

Now if you try to run the examples you will get:

  1. someFuncion("foo", {foo: 42}) -> NO ERROR
  2. someFuncion("foo", {foo: "a string instead of a number"}) -> Type 'string' is not assignable to type 'number'.
  3. someFuncion("foo", {bar: 42}) -> Argument of type '{ bar: number; }' is not assignable to parameter of type '{ foo: number; }'. Object literal may only specify known properties, and 'bar' does not exist in type '{ foo: number; }.

1 Comment

I need the property name "foo" to be dynamic/flexible, unfortunately this solution only works with "foo". Thanks for spending the time to answer though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.