javascript - Bir değerler dizisi ile arayüz tanımla
Eğer input özelliklerine sahip bir sabitim ve input id'lerini ve varsayılan değerini döndüren bir fonksiyonum varsa, şöyle:
const Inputs = [{label: "myInput1", id: "myId1"}, {label: "myInput2" , id: "myId2" }]
const getInputValues = () => Inputs.reduce( (acc, item) => ({...acc, [item.id] : 123 }), {} )
TypeScript'te getInputValues fonksiyonunun dönüş türünü nasıl tanımlayabilirim?
Kod
Cevap #1
Akla gelebilecek tek yol, Inputs sabitinize const assertion kullanmaktır:
const Inputs = [
{label: "myInput1", id: "myId1"},
{label: "myInput2", id: "myId2"},
] as const;
type InputIds = typeof Inputs[number]['id'];
function getInputValues(): Record<InputIds, number> {
return Inputs.reduce((acc, item) => {
return {...acc, [item.id]: 123};
}, {} as Partial<Record<InputIds, number>>) as Record<InputIds, number>;
}
Cevap #2
Burada umabileceğiniz en iyi şey Record<string, number>.
const getInputValues = ():Record<string,number> =>
Inputs.reduce( (acc, item) => ({...acc, [item.id] : 123 }), {})
Daha iyi tür güvenliği için, eriştiğiniz herhangi bir değeri tür kontrolünden geçirmek zorunda kalacağınız Record<string, number | undefined> seçeneğini tercih edebilirsiniz.
