2021/08/05

Array Object In Angular

angular 使用了 typescript,強型別是 ts 大殺器之一,除了簡單的 stringnumber 那些定義以外,array object 使用度也很高,最常見的作法如下。

interface Member {
username: string;
password: string;
}
const members: Member[] = [
{
username: 'chan',
password: '123456'
}
];
console.log(members);

這樣做沒什麼大問題,但設計上我覺得有點卡,因為 interface Member 就是一個單一物件,另一種寫法比較囉唆一點,但我覺得比較好:

interface Member {
username: string;
password: string;
}
interface Members extends Array<Member> {}
const members: Members = [
{
username: 'chan',
password: '123456'
}
];
console.log(members);

這樣調用 Members 時很明確就是要用陣列,而 Member 則可以給 member detail 使用,職責比較清楚,detail 理論上應該是最小單位,但如果 list 部分有自己的需求也可以自行擴充,type alias 也有相同的作法:

type Member = {
username: string;
password: string;
}
type Members = Member[];
const members: Members = [
{
username: 'chan',
password: '123456'
}
];
console.log(members);

沒有留言: