Interface & Funtion trong Typescript (p1)

Trong bài này, chúng ta cùng tìm hiểu về interface & function trong Typescript. 1. Cài đặt ban đầu: NodeJS: https://nodejs.org/en/ ts-node package $npm i ts-node $touch interface.ts 2. Thực hành Đầu tiên chúng ta tạo file mới & định nghĩa một interface như sau: index.ts interfaceWeather{ date: Date; msg:string;} Diễn giải: Interface thời tiết

Trong bài này, chúng ta cùng tìm hiểu về interface & function trong Typescript.

1. Cài đặt ban đầu:

$npm i ts-node
$touch interface.ts

2. Thực hành

Đầu tiên chúng ta tạo file mới & định nghĩa một interface như sau:

index.ts

interfaceWeather{
  date: Date;
  msg:string;}
  • Diễn giải:
    • Interface thời tiết này có 2 props là date & message thông báo.
    • date có annotation là Date
    • msg có annotation là string

Tiếp theo, chúng ta cần tạo một object thỏa mãn cái interface nêu trên:

const todaysWeather: Weather ={
  date:'today',
  msg:'sunny',};

Lúc này typescript lại thông báo lỗi

The expected type comes from property 'date' which is declared here on type 'Weather'

Bây giờ chúng ta sửa lại cái prop date trong interface weather:

const todaysWeather: Weather ={
  date:newDate(),
  msg:'sunny',};

console.log(todaysWeather);

Tiến hành chạy combine run time:
$ts-node functions.ts, kết quả trả về như sau:

{ date:2022-06-29T06:25:51.534Z, msg: 'sunny' }

Bây giờ chúng ta tạo một arrow function như sau:

constlogWeather=(args: Weather)=>{console.log(args.date);console.log(args.msg);};logWeather(todaysWeather);

Kết quả:

2022-06-29T06:38:19.434Z
sunny

Toàn bộ code

interface Weather {
  date: Date;
  msg: string;
}

const todaysWeather: Weather = {
  date: new Date(),
  msg: 'sunny',
};

console.log(todaysWeather);

const logWeather = (args: Weather) => {
  console.log(args.date);
  console.log(args.msg);
};

logWeather(todaysWeather);

Chúng các bạn thành công nhé 😀

Nguồn: viblo.asia

Bài viết liên quan

9 Mẹo lập trình Web “ẩn mình” giúp tiết kiệm hàng giờ đồng hồ

Hầu hết các lập trình viên (kể cả những người giỏi) đều tốn thời gian x

Can GPT-4o Generate Images? All You Need to Know about GPT-4o-image

OpenAI‘s GPT-4o, introduced on March 25, 2025, has revolutionized the way we create visual con

Khi nào nên dùng main, section, article, header, footer, và aside trong HTML5

HTML5 đã giới thiệu các thẻ ngữ nghĩa giúp cấu trúc nội dung web một cách có

So sánh Webhook và API: Khi nào nên sử dụng?

Trong lĩnh vực công nghệ thông tin và phát triển phần mềm, Webhook và API là hai th