Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

307
Views
Typescript I can't index in the object ,which has many maybe object type
interface type1 {
    ttis: string,
    time: string
}

interface type2 {
    time: string,
    c2: number
}

type nameType1 = 'ttis' | 'time';

type nameType2 = 'c2' | 'time';

function testFun (v: type1[] | type2[], yKey: nameType1 | nameType2) {
    for (const item of v) {
        console.log(item[yKey]) // Property 'ttis' does not exist on type 'type1 | type2'.
    }
}

The v array has many types of element that is an object, and I want to index these objects using a yKey, but the error always up show

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Create a generic constraint for the value type, and then use keyof to restrict the allowed keys:

interface Type1 {
    ttis: string,
    time: string
}

interface Type2 {
    time: string,
    c2: number
}

function testFun<T extends Type1 | Type2>(v: T[], yKey: keyof T) {
    for (const item of v) {
        console.log(item[yKey]);
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!