3 回答

TA貢獻1846條經驗 獲得超7個贊
你可以用擴展類型做很多事情。
正如@SnailCrusher 所示,您可以靜態定義返回類型。還有一種方法可以動態地將類型分配給返回的道具:
// this interface defines potential parameters to the methods
interface Tokens {
foo: number,
bar: string,
}
// return one prop in the result object
// this methods only accept keys of the interface Tokens as valid inputs
function test<K extends keyof Tokens>(key: K) {
switch(key) {
case 'foo': return { [key]: 0 } as {[prop in K]: Tokens[K]}
case 'bar': return { [key]: '0' } as {[prop in K]: Tokens[K]};
}
return { [key]: undefined } as {[prop in K]: Tokens[K]}
}
const bar = test('bar') // { bar: string }
const foo = test('foo') // { foo: number }
// return full interface in the result object
// the given token will be set an all other props will be optional
function test2<K extends keyof Tokens>(key: K) {
return { [key]: 6 } as {[prop in K]: Tokens[K]} & {[P in keyof Tokens]?: Tokens[P];}
}
const bar2 = test2('bar') // { foo?: number; bar: string; }
const foo2 = test2('foo') // { foo: number; bar?: string; }
這還將在有效參數上為您的 IDE 添加豐富的上下文。
您可以在 Typescript 文檔中閱讀更多內容: https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types-and-index-signatures

TA貢獻1829條經驗 獲得超4個贊
稍微調整一下第一次嘗試,這似乎有效:
function test<K extends string>(key: K) {
return { [key]: 6 } as {[prop in K]: number}
}
const foo = test('bar') // { bar: number }
不過,不得不施放它對我來說似乎有點奇怪。

TA貢獻1815條經驗 獲得超13個贊
我不明白為什么你在這里需要泛型,這與簡單地做相反
function test(key: string): { [key: string]: number } {
return { [key]: 6 };
}
添加回答
舉報