“TypeScript Uniions” Ответ

TypeScript Uniions

type MyBool = true | false;
Puzzled Puffin

Типовой дискриминационные профсоюзы

// Object unions with variants of a similiar property, but different
// key names. Need to add a common property to connect them.
interface Circle {
  kind: "circle";
  radius: number;
}
 
interface Square {
  kind: "square";
  sideLength: number;
}
 
type Shape = Circle | Square;

// TypeScript can now narrow out the members
function getArea (shape: Shape) {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius ** 2 // safely accessing shape.radius
  }
}

// Alternatively use a switch statement
switch(shape.kind) {
  case 'circle':
    return Math.PI * shape.radius ** 2
  case 'square':
    return shape.sideLength ** 2
Stupid Scarab

Ответы похожие на “TypeScript Uniions”

Вопросы похожие на “TypeScript Uniions”

Смотреть популярные ответы по языку

Смотреть другие языки программирования