亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

TypeScript:你能根據函數的參數定義一個返回類型結構嗎?

TypeScript:你能根據函數的參數定義一個返回類型結構嗎?

largeQ 2023-03-24 16:38:06
我正在嘗試創建一個函數,它將接受一個字符串參數并返回一個以該字符串為鍵的對象。例如(偽代碼): test('bar') => {bar: ...}我不確定如何為這個函數獲取正確的返回類型。這段代碼給了我正確的返回類型,但 TS 編譯器認為我返回的對象與返回類型不匹配?function test<K extends string>(key: K):{[prop in K]: number} {  return { [key]: 6 } // error: not assignable}const foo = test<'bar'>('bar')// foo type: {bar: number} // return type is good像這樣的東西會很好用。但是沒有給我正在尋找的強類型返回類型:function test2<K extends string>(key: K){  return { [key]: 6 }}const foo2 = test2<'bar'>('bar')// foo2 type: {[x: string]: number}  // no good對此的任何幫助將不勝感激!
查看完整描述

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


查看完整回答
反對 回復 2023-03-24
?
浮云間

TA貢獻1829條經驗 獲得超4個贊

稍微調整一下第一次嘗試,這似乎有效:


function test<K extends string>(key: K) {

  return { [key]: 6 } as {[prop in K]: number}

}


const foo = test('bar') // { bar: number }

不過,不得不施放它對我來說似乎有點奇怪。


查看完整回答
反對 回復 2023-03-24
?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

我不明白為什么你在這里需要泛型,這與簡單地做相反


function test(key: string): { [key: string]: number } {

  return { [key]: 6 };

}


查看完整回答
反對 回復 2023-03-24
  • 3 回答
  • 0 關注
  • 160 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號