ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

复杂类型脚本类型定义开发提示

2023-08-10 19:56:20  阅读:149  来源: 互联网

标签:脚本 API 变量


1.普通物体

const fullName: { firstName: string; lastName: string } = {
  firstName: 'Lakshmanan',
  lastName: 'Arumugam'
};

console.log(fullName.firstName)
// Output Lakshmanan

2.数字枚举变量赋值

enum Weekend {
  Friday = 5,
  Saturday,
  Sunday
};

// Assign a valid value of Weekend
const today: Weekend = 7;  // No bug
console.log(`Today is the ${today}th day of the week!`);
// Output: "Today is the 7th day of the week!"

3.元组上的数组类型推断

const threeWords: [ string, number, string] = ['Won', 5, 'games'];

// Calling .concat() on a tuple returns an array
let moreWords = threeWords.concat(['last', 'night']);

// An array is expandable
moreWords[5] = ('!');

console.log(moreWords);
// Output: ["Won", 5, "games", "last", "night", "!"]

4.基本类型的数组

const marks: number[] = [ 100, 500, 300, 200, 400 ]

console.log("mark value", marks[0])

// Output: 100

5.数组通用类型

// zipcodes is an array of strings
let zipcodes: Array<string> = ['03255', '02134', '08002', '03063'];

// Pushing a number to zipcodes will generate an error
// Error: Argument of type 'number' is not assignable to parameter of type 'string'.
zipcodes.push(05115);

6.对象键字符串和值

interface StatusObject {
    id: number;
    name: string;
}

interface Status {
    [key: string]: StatusObject
}

const statusValues: Status = {
    "0": { "id": 0, "name": "Available" },
    "1": { "id": 1, "name": "Ready" },
    "2": { "id": 2, "name": "Started" }
 };

 console.log(statusValues["0"].name)
//  Output: "Available"

7.对象数组


interface Color {
    color: string;
    value: string;
}

const colors:Color[] = [
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    }
]

console.log(colors[0].color)
// Output: "red"

8.高度嵌套的对象和数组值

interface Bakery {
    id:      string;
    type:    string;
    name:    string;
    ppu:     number;
    batters: Batters;
    topping: Topping[];
}

interface Batters {
    batter: Topping[];
}

interface Topping {
    id:   string;
    type: string;
}


const bakery: Bakery =  {
  "id": "0001",
  "type": "donut",
  "name": "Cake",
  "ppu": 0.55,
  "batters": {
    "batter": [
      {
        "id": "1001",
        "type": "Regular"
      }
    ]
  },
  "topping": [
    {
      "id": "5001",
      "type": "None"
    }
  ]
}

console.log(bakery.batters.batter[0].id)
// Output: "1001"

9.对象值必填字段(实用性)

interface Car {
  make: string;
  model: string;
  mileage?: number;
}

let FordCard: Required<Car> = {
  make: 'Ford',
  model: 'Focus',
  mileage: 12000 // `Required` forces mileage to be defined
};

let KiaCard: Required<Car> = {
  make: 'Ford',
  model: 'Focus'
};

//Error
//Property 'mileage' is missing in type '{ make: string; model: string; }' but required in type 'Required<Car>'.

10。继承现有类型定义

interface Brand {
  brand: string;
}

interface Model extends Brand {
  model: string;
}

class Car implements Model {
  brand;
  model;
  constructor(brand: string, model: string) {
    this.brand = brand;
    this.model = model;
  }
  log() {
    console.log(`Drive a ${this.brand} ${this.model} today!`);
  }
}

const myCar: Car = new Car('Nissan', 'Sentra'); 
myCar.log();

// Output: "Drive a Nissan Sentra today!"

11.复杂的API响应类型

// Define types for product and customer
type Product = {
  id: number;
  name: string;
  price: number;
  stock: number;
};

type Customer = {
  id: number;
  name: string;
  email: string;
};

// Define types for order and order status
type OrderStatus = "pending" | "processing" | "shipped" | "delivered" | "cancelled";

type Order = {
  id: number;
  customer: Customer;
  products: { product: Product; quantity: number }[];
  status: OrderStatus;
};

// Define type for the inventory management system
type InventorySystem = {
  products: Product[];
  customers: Customer[];
  orders: Order[];
  addProduct: (product: Product) => void;
  addCustomer: (customer: Customer) => void;
  placeOrder: (order: Order) => void;
};

// Create an instance of the inventory management system
const inventory: InventorySystem = {
  products: [],
  customers: [],
  orders: [],
  addProduct(product) {
    this.products.push(product);
  },
  addCustomer(customer) {
    this.customers.push(customer);
  },
  placeOrder(order) {
    // Check if products are in stock before placing the order
    for (const { product, quantity } of order.products) {
      const availableProduct = this.products.find(p => p.id === product.id);
      if (!availableProduct || availableProduct.stock < quantity) {
        throw new Error(`Product ${product.name} is out of stock.`);
      }
    }

    // Deduct ordered quantities from the product stock
    for (const { product, quantity } of order.products) {
      const availableProduct = this.products.find(p => p.id === product.id);
      if (availableProduct) {
        availableProduct.stock -= quantity;
      }
    }

    this.orders.push(order);
  },
};

// Example usage
const newProduct: Product = { id: 1, name: "Widget", price: 10, stock: 100 };
inventory.addProduct(newProduct);

const newCustomer: Customer = { id: 1, name: "Alice", email: "alice@example.com" };
inventory.addCustomer(newCustomer);

const newOrder: Order = {
  id: 1,
  customer: newCustomer,
  products: [{ product: newProduct, quantity: 3 }],
  status: "pending",
};
inventory.placeOrder(newOrder);

console.log(inventory);
// Output: 
// {
//   "products": [
//     {
//       "id": 1,
//       "name": "Widget",
//       "price": 10,
//       "stock": 97
//     }
//   ],
//   "customers": [
//     {
//       "id": 1,
//       "name": "Alice",
//       "email": "alice@example.com"
//     }
//   ],
//   "orders": [
//     {
//       "id": 1,
//       "customer": {
//         "id": 1,
//         "name": "Alice",
//         "email": "alice@example.com"
//       },
//       "products": [
//         {
//           "product": {
//             "id": 1,
//             "name": "Widget",
//             "price": 10,
//             "stock": 97
//           },
//           "quantity": 3
//         }
//       ],
//       "status": "pending"
//     }
//   ]
// }

标签:脚本,API,变量
来源:

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有