typescript-generics

How TypeScript infers callbacks arguments type

时光总嘲笑我的痴心妄想 提交于 2021-01-07 02:49:39
问题 My question is based on this question and answer Let's say we have next code: const myFn = <T,>(p: { a: (n: number) => T, b: (o: T) => void, }) => { // ... } myFn({ a: () => ({ n: 0 }), // Parameter of a is ignored b: o => { o.n }, // Works! }) myFn({ a: i => ({ n: 0 }), // Parameter i is used b: o => { o.n }, // Error at o: Object is of type 'unknown'.ts(2571) }) I was able to fix it. It works with extra generic: const myFn = <T,>(p: { a: (n: number) => T, b: <U extends T /* EXTRA U generic

Typed Generic Key Value Interface in Typescript

混江龙づ霸主 提交于 2020-12-29 06:09:10
问题 I have the following example Object: let foo: Foo = { 'key1': { default: 'foo', fn: (val:string) => val }, 'key2': { default: 42, fn: (val:number) => val }, // this should throw an error, because type of default and fn don't match 'key3': { default: true, fn: (val:string) => val } } The Interface should look something like this: interface Foo { [key: string]: { default: T, fn: (val:T) => any } } This of course doesn't work, because there's no T defined. So I thought about doing this:

Typescript: How to use a generic parameter as object key

夙愿已清 提交于 2020-12-02 11:49:28
问题 Is it possible to write an interface that accepts a string constant as one of its parameters, and uses that as the key of an object? For instance, assuming I make two different GraphQL requests, both of which return a User , but under different key names: const userByIdResult = { data: { userById: { id: 123, username: 'joseph' } } } const userByUsernameResult = { data: { userByUsername: { id: 123, username: 'joseph' } } } I would imagine writing a generic interface would go something like