ค้นหาเว็บไซต์

typescript - ด้านซ้ายของคำสั่ง 'for...in' ไม่สามารถใช้การระบุประเภทได้


ฉันจะแก้ไขข้อผิดพลาด The left-hand side of a 'for...in' statement cannot use a type annotation. ได้อย่างไร? โค้ดที่ไม่สามารถคอมไพล์ได้คือการวนลูป for...in ธรรมดา:

const roles = ['a', 'b', 'c'] as const
type Roles = typeof roles[number] // 'a' | 'b' | 'c'

const roles = {
  'a': '...',
  'b': '...',
  'c': '...',
}

for (const role: Roles in roles) {
  const isRole = roles.includes(roles)
}

ฉันเข้าใจว่าการพิมพ์ค่าคงที่ role เป็นไปไม่ได้ แต่ถ้าฉันไม่ทำ const isRole=roles.includes(roles) จะไม่ถูกต้อง: Argument of type 'string' is not assignable to parameter of type '"a" | "b" | "c"'.

คำตอบ #1

ฉันอาจจะผิดเพราะฉันทำแบบนี้เฉพาะกับลูป of เท่านั้น แต่คุณน่าจะสามารถบังคับการกำหนดประเภทบนคอลเลกชัน (ด้านขวา) ซึ่งจะบอกประเภทของไอเท็มได้

ตัวอย่างเช่น:

for (role in roles as Roles[]) 

นี่ควรทำให้แต่ละองค์ประกอบเป็นประเภท Roles

คำตอบ #2

คุณสามารถประกาศตัวแปรแบบ let ในสโคปเดียวกันและกำหนดชนิดของตัวแปรได้ ตัวอย่างของคุณอยู่ด้านล่าง


    const roles = ['a', 'b', 'c'] as const
    type Roles = typeof roles[number] // 'a' | 'b' | 'c'
    
    const roles = {
      'a': '...',
      'b': '...',
      'c': '...',
    }
    
    let role: Roles;
    
    for (role in roles) {
      const isRole = roles.includes(roles)
    }

บทความที่เกี่ยวข้อง