Skip to content

how define a dynamic type with optional argument ? #17219

Answered by JiatLn
baixiaoyu2997 asked this question in Q&A
Discussion options

You must be logged in to vote

hope it could work~

function useTest<T extends { text: string }>(options: { text: string }): { getXXX: () => string }
function useTest<T extends Omit<Record<string, any>, 'text'>>(options: any): { getXXX: (options: { text: string }) => string }
function useTest<T extends Omit<Record<string, any>, 'text'>>(): { getXXX: (options: { text: string }) => string }


function useTest(useTestOptions: { text?: string } = {}) {

  const getXXX = (options?: { text: string }) => {
    return options.text || useTestOptions.text
  }

  return {
    getXXX
  }
}

const { getXXX: f1 } = useTest({ text: '123' })
const { getXXX: f2 } = useTest()
const { getXXX: f3 } = useTest({})

f1()
f2({ 'text': '123' })
/…

Replies: 3 comments 4 replies

Comment options

You must be logged in to vote
2 replies
@baixiaoyu2997
Comment options

@baboon-king
Comment options

Comment options

You must be logged in to vote
2 replies
@baboon-king
Comment options

@baixiaoyu2997
Comment options

Answer selected by baixiaoyu2997
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants