javascript - Typescript indeks imzası için farklı türler


Aşağıdaki interface'e sahibim.

interface IDetails {
  name: string;
  age: number;
}

interface IConfig {
  appName: string;
  userDetails: IDetails;
  [key: string]: string | IDetails
}

const details: IConfig = {
  appName: 'test',
  userDetails: {
    name: 'xyz',
    age: 67,
  },
}

const t: string = 'userDetails'
const name: string = details[t].name
//                              ^^^^ 
// throws the following error
//
// Property 'name' does not exist on type 'string | IDetails'.
//  Property 'name' does not exist on type 'string'.

Birden fazla tür/interfeysi anahtar imzasına atamaya çalıştığımda bu hatayı alıyorum. [key: string]: any kullanabileceğimi biliyorum. Ama bunu genelleştirmek istemiyorum. Bunu çalıştırmanın herhangi bir yolu var mı?

TypeScript Oyun Alanı bağlantısı

Cevap #1

Eğer details özelliklerine dinamik olarak erişecekseniz, o zaman tip koruyucular kullanmanız daha iyi olur:

function isDetails(obj: string | IDetails): obj is IDetails {
    return Object.keys(obj).length === 2 && typeof obj["name"] === "string" && typeof obj["age"] === "number";
}

O zaman şunu yapabilirsin:

if (isDetails(details[t])) {
    // details[t].name should be fine with the compiler
}