kaytrance
kaytrance

Reputation: 2757

Limit function parameter type only to keys of interface with specific type

Lets assume I have an interface called dto. It has several fields in it with different types.

I want to have a function that can only accept paramater whos name is one of keys of dto and whos type is only number.

interface dto {
    aaa: string,
    bbb: number,
    ccc: boolean,
    ddd: number,
}

const variable = <dto> {
    aaa: "hello",
    bbb: 42,
    ccc: false,
    ddd: 914    
};

function test(param: <SOME MAGIC HERE>): number {
    return variable[param] + 10;
}

console.log(test("aaa")); // error, because dto.aaa has type of string
console.log(test("ccc")); // error, because dto.ccc has type of boolean
console.log(test("eee")); // error, because "eee" id not among keys of dto
console.log(test("bbb")); // ok, will return 52, because dto.bbb has type of number and "bbb" is among keys of dto

Is it even possible?

Upvotes: 3

Views: 266

Answers (1)

Yes

type OnlyNumbers<T> = {
  [Prop in keyof T]: T[Prop] extends number ? Prop : never
}[keyof T]

function test(param: OnlyNumbers<dto>): number {
  return variable[param] + 10;
}

enter image description here

Upvotes: 4

Related Questions