简体   繁体   中英

How to get a literal type from a function argument for a computed property name?

please consider the following code:

const fn = (name: string) => {
  return { [name]: "some txt" };
};

const res = fn("books"); // books or any other string

TS recognizes res as the following type:

const res: {
  [x: string]: string;
}

I'd like TS to know that res has a property books

const res: {
  books: string;
}

I tried many things but nothing seems to work. Is it possible at all? Is it a known issue?

You have to create a generic function like this:

const fn = <T extends string>(name: T): { [key in T]: string } => {
  return { [name]: "some txt" } as any;
};

const res = fn("books");

It seems like a bug in TypeScript that it doesn't allow such things, that's why you need the as any . See here for an interactive example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM