Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
// MyComponent/composition.tsx
const MyComponent = (sitecoreData) => {
return sitecoreData;
};// MyComponent/index.tsx
/** technically, you would want to provide types in a Typescript file,
* but we're just trying to get some data here.
*/
const MyComponent = (scData) => {
console.log(scData);
return <div>{JSON.stringify(scData)}</div>;
};
// Now you can copy the payload from your browser and paste it into your brand new data file!// story.js
import React from "react";
import MyComponent from "./index";
import { MyComponent as MyComponentComposition } from "../../lib/composition";
import Data from "./data";
/**
* create a variable with data that is in the shape that your component will be
* expecting, as it would be from your composition file.
* Again, this is necessary since the composition function is not called by Storybook.
*/
const props = MyComponentComposition(Data);
const Template = (args) => <MyComponent {...args} />;
export const Primary = Template.bind({});
Primary.args = {
/* here you can spread those props into your Storybook file, making data
* available to your component as it would be on the actual live page.
*/
...props,
};const { compositionFunction, component } = Composition(NavCard)(({ fields, params }) => {
const items = fields?.items.reduce(
(acc: Parameters<typeof NavCard>[0]['items'], curr: typeof fields) => {
return [
{
...
analytics: {
category: 'nav-card_rectangular',
label: title?.value || '',
action: [cta?.text?.value, cta?.href].filter(Boolean).join(' | '),
guid: link?.value?.id || '',
event: 'event-click',
},
},
];
},
[]
);import track from 'src/lib/Analytics';
...
const ComponentName = ({
...
analytics,
}: PropsType) => {
...
<Button
...
onClick={() => track.component(analytics)}
>
Click Me!
</Button>sudo vim /etc/hosts 1. Add:
```
{
"sitecore": {
"instancePath": "",
"apiKey": "{9F777224-3275-4D56-BD29-371FB3C00821}",
"deploySecret": "",
"deployUrl": "",
"layoutServiceHost": "https: ```
HTTPS=true
```
This will allow you to use `https:const componentAlias = {
HeroCarousel: "Hero",
HeroCarouselNocache: "Hero",
JssAccordion: "Accordion",
// ...
};<Component title={fields.PodItemLink?.value?.text} /><Component title={title} />// composition/index.js
const QuickLinks = ({ fields }) => {
const items = fields?.QuickLinkItems?.reduce(
(acc, curr) => [
...acc,
{
image: { ...curr.Icon?.value },
link: curr.Link?.value?.href,
title: curr.Title?.value,
id: curr.Id,
},
],
[]
);
return { items };
};// components/QuickLinks/index.tsx
const QuickLinks = ({ items }: { items: Array<ComponentTypes> }) => (
<QuickLinksWrapper>
{items?.map(({ id, ...rest }, index) => (
<QuickLinksItem index={index} length={items.length} key={id} {...rest} />
))}
</QuickLinksWrapper>
);<div className="js-form text-blue-dark..." /><div className="text-blue transition-all md:px-32 mt-12 flex bg-black w-20 duration-500 md:block px-24 lg:w-16 lg:px-48" /><div className="w-20 lg:w-16 mt-12 px-24 md:px-32 lg:px-48 flex md:block text-blue bg-black transition-all duration-500 /><Component title={fields.PodItemLink?.value?.text} /><Component title={title} />// composition/index.js
const QuickLinks = ({ fields }) => {
const items = fields?.QuickLinkItems?.reduce(
(acc, curr) => [
...acc,
{
image: { ...curr.Icon?.value },
link: curr.Link?.value?.href,
title: curr.Title?.value,
id: curr.Id,
},
],
[]
);
return { items };
};// components/QuickLinks/index.tsx
const QuickLinks = ({ items }: { items: Array<ComponentTypes> }) => (
<QuickLinksWrapper>
{items?.map(({ id, ...rest }, index) => (
<QuickLinksItem index={index} length={items.length} key={id} {...rest} />
))}
</QuickLinksWrapper>
);import React, { useState } from "react";
const Button = () => {
const [count, setCount] = useState(0);
return <button onClick={setCount(count + 1)}>clicked {count} times!</button>;
};const ChildComponent = () => {
return (
<Fragment>
<div>Title</div>
<div>SubTitle</div>
</Fragment>
);
};const ChildComponent = () => {
return (
<>
<div>Title</div>
<div>SubTitle</div>
</>
);
};const Component = ({ items }: { items: Array<ComponentTypes> }) =>
items?.map(({ id, ...rest }, index) => (
<Fragment key={id}>
<div>The title</div>
<InnerComponent index={id} length={items.length} {...rest} />
</Fragment>
));const ChildComponent = () => {
return <div>The Child</div>;
};const ChildComponent = () => {
return (
<div>
<Component />
<Component />
<Component />
</div>
);
};const ChildComponent = () => <div>The Child</div>;const ChildComponent = () => (
<div>
<Component />
<Component />
<Component />
</div>
);const ChildComponent = () => <div>The child</div>;
const ParentComponent = () => (
<>
<h1>The Title</h1>
<ChildComponent />
</>
);
export { ChildComponent };
export default ParentComponent;const QuickLinks = ({ items }: { items: Array<ComponentTypes> }) => (
<QuickLinksWrapper>
{items?.map(({ image, link, title, id }, index) => (
<QuickLinksItem
image={image}
index={index}
length={items.length}
link={link}
title={title}
key={id}
/>
))}
</QuickLinksWrapper>
);const QuickLinks = ({ items }: { items: Array<ComponentTypes> }) => (
<QuickLinksWrapper>
{items?.map(({ id, ...rest }, index) => (
<QuickLinksItem index={index} length={items.length} key={id} {...rest} />
))}
</QuickLinksWrapper>
);const DataReport = ({ items }: { items: Array<string> }) => (
<table>
<tr className="bg-teal-dark text-lg text-white">
<td className="cell-class">NAME</td>
<td className="cell-class">HOURS</td>
</tr>
{items.map(({ hours, name }, index) => (
<tr className="bg-transparent text-lg text-teal-dark" key={index}>
<td className="cell-class">{name}</td>
<td className="cell-class">{hours}</td>
</tr>
))}
</table>
);const TableCell = ({ children }) => (
<td className="cell-class">{children}</td>
);
const TableRow = ({ children, isHeader }) => {
const class = isHeader ? 'bg-teal-dark text-white' : 'bg-transparent text-teal-dark'
return <tr className={`${class} text-lg`}>{children}</td>
};
const DataReport = ({ items }: { items: Array<string> }) => (
<table>
<TableRow isHeader={true}>
<TableCell>NAME</TableCell>
<TableCell>HOURS</TableCell>
</TableRow>
{items.map(({ hours, name }, index) => (
<TableRow key={index}>
<TableCell>{name}</TableCell>
<TableCell>{hours}</TableCell>
</TableRow>
))}
</table>
);npm run storybookexport const NoIcons = Template.bind();
NoIcons.args = {
items: itemsOptions["3"],
};export const Icons = Template.bind({});
Icons.args = {
items: itemsOptions["5"],
};export default {
title: "Components/Accordion",
component: AccordionComponent,
argTypes: {
theme: {
name: "Theme",
},
closeOthers: {
name: "One Panel Open At A Time",
},
},
};
const Template = (args) => <AccordionComponent {...args} />;
export const Primary = Template.bind({});
Primary.args = {
...props,
};argTypes: {
backgroundColor: {
control: {
type: 'radio',
options: ['white', 'gray'],
},
defaultValue: 'white',
},
},argTypes: {
items: {
name: 'How many items?',
control: {
type: 'select',
options: {
...itemsPrimary,
},
},
},
},argTypes: {
title: {
control: {
type: 'text',
},
},
subtitle: {
control: {
type: 'text',
},
},
link: {
control: 'boolean',
},
ctaType: {
control: {
type: 'inline-radio',
options: ['ImageSlide', 'VideoSlide'],
},
},
},import React from "react";
import MyComponent from "./index";
import { Data } from "./data";
import { MyComponent as MyComponentComposition } from "../../lib/composition";
const props = MyComponentComposition({ fields: Data });
export default {
title: "Components/MyComponent",
component: MyComponent,
argTypes: {
backgroundColor: {
control: {
type: "radio",
options: ["white", "gray"],
},
defaultValue: "white",
},
},
};
const Template = (args) => <MyComponent {...args} />;
export const Primary = Template.bind({});
Primary.args = {
...props,
};import React from 'react';
import MyComponent from './index';
import { Data } from './data';
......
import { MyComponent as MyComponentComposition } from '../../lib/composition';
const props = MyComponentComposition({ fields: Data });
......
export default {
title: 'Components/MyComponent',
component: MyComponent,
argTypes: {
backgroundColor: {
control: {
type: 'radio',
options: ['white', 'gray'],
},
defaultValue: 'white',
},
},
};
......
const Template = args => <MyComponent {...args} />;
export const Primary = Template.bind({});
Primary.args = {
...props,
};...
import { storybookCustomArgs, createStoryOptions } from 'src/lib/helpers';
const props = BulletedOverviewComposition(Data);
const itemsToShow = createStoryOptions(props.items);
export default {
title: 'Components/Bulleted Overview',
component: BulletedOverview,
argTypes: {
...storybookCustomArgs(props, BulletedOverview, [], false),
items: {
name: 'How many items?',
control: {
type: 'select',
options: {
...itemsToShow,
},
},
},
},
};
...<SingleStepForm />{
componentName: 'ContentMain',
content: [{
uid: '',
componentName: 'Single Step Form',
dataSource: '',
fields: {
ModelJson: {
value: '[ { "title":"Form Name", "fields":{ "Name":{ "label":"Form Name", "type":"input", "value":"Form Name", "name":"Name" }, "Id":{ "label":"Id", "type":"hidden", "value":"", "name":"Id" } }, "fresh":true }, { "title":"Text Input", "fields":{ "FormId":{ "label":"FormId", "type":"hidden", "value":"stepOne", "name":"FormId" }, "Name":{ "label":"Name", "type":"hidden", "value":"textinput", "name":"Name" }, "Id":{ "label":"Id", "type":"input", "value":"fixtureName", "name":"Id" }, "Label":{ "label":"Label", "type":"input", "value":"Fixture Selection", "name":"Label" }, "BackEndLabel":{ "label":"BackEnd Label", "type":"input", "value":"Fixture Selection", "name":"BackEndLabel" }, "Value":{ "label":"Default Value", "type":"input", "value":"", "name":"Value" }, "DefaultValueSource":{ "label":"Default Value Source", "type":"select", "value":[ { "value":"None", "selected":false, "label":"None" }, { "value":"cookie", "selected":true, "label":"Cookie" } ], "name":"DefaultValueSource" }, "DefaultValueKey":{ "label":"Default Value Source Key", "type":"input", "value":"fixtureName", "name":"DefaultValueKey"}]
}
}
}]
}- `createdFields` is memoized to cache the original value and keep it from re-rendering each cycle
- The `false` parameter signifies that its not to return a multidimensional array, just a single array
5. `createFormInit()` is a 'factory' for both `<SingleStepForm />` and `<MultiStepForm />`. We will focus on what happens if this is called from `<SingleStepForm />`.
```typescript
const createFormInit: {
(arr: Array<ParsedFormModel>, multi: true): CFReturnType[][];
(arr: Array<ParsedFormModel>, multi: false): CFReturnType[];
} = (arr: Array<ParsedFormModel>, multi: boolean): any => {
return multi ? multiStepFormFields(arr) : parseFields(arr);
};const parseFields = (arr: Array<ParsedFormModel>) => {
const items = arr.reduce((acc: Array<CFReturnType | null>, curr) => {
const formField = createForm(curr);
return [...acc, formField];
}, []);
// filter out any null values due to early returns from hidden fields
return items.filter(Boolean) as Array<CFReturnType>;
};- `dataMap`
- `dataMap` is an object with `inputMap` values as the key and related props as the value. All of these will contain a 'file' value. This is the name of the React component that will be dynamically imported, and some of them will contain a 'props' value. Props is an object that contains more details for that particular input type such as type, icon, masking function etc..
```javascript
```
const dataMap: CFMappingType["dataMap"] = {
// ...
input: {
file: "Input",
props: { type: "text" },
},
phone: {
file: "Input",
props: {
type: "tel",
icon: "phone",
mask: masks.tel,
},
},
radio: {
file: "RadioGroup",
},
// ...
};2. Inside `createForm()` it will take the incoming field name and use it to index `inputMap`. At this point one of three things will happen:
- It will find a match and return that input type
- It will return a null value (these are currently hidden fields or unimportant fields)
- It will return undefined\
\
If it returns a type we will continue, if it returns a null we return a null out of createForm(), if its undefined we then assume and assign this field with a type 'input'
3. Now that we have the field type (the `inputType` value), we use this to index `dataMap` and return the file and or props from that
- We take this file name and dynamically import that component (ie: 'Input', 'Heading', 'RadioGroup', 'Tabs', etc..)
```javascript4. We then now build our return object which gets added to the array in `parseFields()` and gets sent back to `<SingleStepForm />`
```javascript
return {
Component,
data: getData(fields, title),
file,
formName: fields?.FormId?.value,
id: uid(32),
props: {
columns: getColumnWidth(fields.ColumnWidth?.value),
...props,
},
validations: getValidations(file, fields, props?.type),
};const getData: GetDataProps = ({ fields, title }) => ({
customValidationErrorMsg:
fields?.CustomValidationErrorMsg?.value || "field is required",
items: parseItems(fields?.InputItems?.value),
label: fields?.Label?.value || "",
maxLength: parseInt(fields?.MaximumLength?.value) || 524288,
minLength: parseInt(fields?.MinimumLength?.value) || 0,
name: fields?.Name?.value,
placeholder: fields?.PlaceholderText?.value,
required: fields?.Required?.value || false,
tabs: fields?.Tabs?.value.split("\n") || [],
title,
toolTipText: fields?.TooltipText?.value,
});const getValidations: GetValidationProps = (file, fields, regex = "") => {
const skipValidation = ["Heading", "Recaptcha", "Tabs"];
let pattern;
if (file && skipValidation.includes(file)) return null;
// Validations will usually come through as a string value from sitecore
// but can also come through as an array of objects, these have the type 'select'
// We first need to parse through this array and grab the value of the selected validation pattern
if (fields?.ValidationPattern?.type === "select") {
pattern = getSelectedValue(fields.ValidationPattern.value);
} else {
pattern = fields?.ValidationPattern?.value;
}
return {
shouldConfirm: fields?.AppearsOnFormConfirmation?.value,
validationPattern:
// 1. by regex in mapping props (phone, ssn)
// 2. by named regex pattern coming from Sitecore
regexMap[regex] || regexMap[pattern],
};
}; return (
<div className="relative">
<InputText {...propData} />
<div className="hidden lg:block absolute top-0 right-0 mt-4 lg:-mr-48">
<Tooltip error={Boolean(errors[name])} message={toolTipText} />
</div>
</div>
);
};
```[[form stepper element], [...first section fields], [...second section fields] ...etc]const formModel: Array<ParsedFormModel> = JSON.parse(modelJson.value);
const createdFields = useMemo(() => createFormInit(formModel, true), []);
const createdFieldsWithoutTabs = [...createdFields.slice(1), []];
const createdFieldsOnlyTabFields = [
...createdFields[0][0].data.tabs,
"Confirmation",
];
// ... return
<FormComponent onSubmit={handleFormSubmit}>
<FormStepper activeIndex={activeIndex} content={createdFieldsOnlyTabFields} />
{createdFieldsWithoutTabs.map((innerArray, index) =>
innerArray.map(
({ Component, data, id, props, validations, ...rest }: CFReturnType) => {
return (
<FieldWrapper
className={index === activeIndex ? "block" : "hidden"}
columns={props?.columns}
key={id}
>
<Component
register={register({
pattern: regexPattern(validations),
required: isRequired(data),
validate: {
match: (value: string) =>
matchingEmails(
name.toLowerCase(),
value,
getValues(["email", "emailconf"])
),
},
})}
{...{ data, errors, name, props, ...rest }}
/>
</FieldWrapper>
);
}
)
)}
{isLastStep && <ConfirmationStep data={confirmedValues} {...{ fields }} />}
<ButtonWrapper />
</FormComponent>;[
{
"title": "Radio List",
"fields": {
"FormId": {
"label": "FormId",
"type": "hidden",
"value": "stepOne",
"name": "FormId"
},
"Name": {
"label": "Name",
"type": "input",
"value": "Are you a customer requesting a single light for your yard or property?",
"name": "Name"
},
"Label": {
"label": "Label",
"type": "input",
"value": "Are you a customer requesting a single light for your yard or property?",
"name": "Label"
},
"BackEndLabel": {
"label": "BackEnd Label",
"type": "input",
"value": "Are you a customer requesting a single light for your yard or property?",
"name": "BackEndLabel"
},
"GroupName": {
"label": "Group Name",
"type": "input",
"value": "GroupName",
"name": "GroupName"
},
"Value": {
"label": "Default Value",
"type": "input",
"value": "",
"name": "Value"
},
"Id": {
"label": "Id",
"type": "input",
"value": "radiolist",
"name": "Id"
},
"TooltipText": {
"label": "Tooltip Text",
"type": "input",
"value": "",
"name": "TooltipText"
},
"CustomValidationErrorMsg": {
"label": "Custom Validation Err. Msg.",
"type": "input",
"value": "Please pick an option.",
"name": "CustomValidationErrorMsg"
},
"AppearsOnFormConfirmation": {
"label": "Appear on Confirmation",
"type": "checkbox",
"value": true,
"name": "AppearsOnFormConfirmation"
},
"Required": {
"label": "Required",
"type": "checkbox",
"value": true,
"name": "Required"
},
"InputItems": {
"label": "Items",
"type": "radiolist",
"value": "[{\"text\":\"Yes\",\"value\":\"Yes\"},{\"text\":\"No\",\"value\":\"No\"}]",
"name": "InputItems"
}
},
"fresh": true
},
{
"title": "Section Header",
"fields": {
"FormId": {
"label": "FormId",
"type": "hidden",
"value": "stepOne",
"name": "FormId"
},
"Name": {
"label": "Name",
"type": "hidden",
"value": "sectionhdr",
"name": "Name"
},
"Label": {
"label": "Label",
"type": "input",
"value": "Name & Address",
"name": "Label"
},
"BackEndLabel": {
"label": "BackEnd Label",
"type": "input",
"value": "Name & Address",
"name": "BackEndLabel"
},
"Id": {
"label": "Id",
"type": "hidden",
"value": "sectionhdr",
"name": "Id"
}
},
"fresh": true
},
{
"title": "First Name",
"fields": {
"FormId": {
"label": "FormId",
"type": "hidden",
"value": "stepOne",
"name": "FormId"
},
"Name": {
"label": "Name",
"type": "hidden",
"value": "FirstName",
"name": "Name"
},
"Id": {
"label": "Id",
"type": "hidden",
"value": "FirstName",
"name": "Id"
},
"Label": {
"label": "Label",
"type": "hidden",
"value": "First Name",
"name": "Label"
},
"BackEndLabel": {
"label": "BackEnd Label",
"type": "hidden",
"value": "First Name",
"name": "BackEndLabel"
},
"Value": {
"label": "Default Value",
"type": "hidden",
"value": "",
"name": "Value"
},
"ValidationPattern": {
"label": "Validation Rule",
"type": "hidden",
"value": "lettersWhiteSpace",
"name": "ValidationPattern"
},
"TooltipText": {
"label": "Tooltip Text",
"type": "input",
"value": "",
"name": "TooltipText"
},
"CustomValidationErrorMsg": {
"label": "Custom Validation Err. Msg.",
"type": "hidden",
"value": "Please enter a first name.",
"name": "CustomValidationErrorMsg"
},
"AppearsOnFormConfirmation": {
"label": "Appear on Confirmation",
"type": "checkbox",
"value": false,
"name": "AppearsOnFormConfirmation"
},
"Required": {
"label": "Required",
"type": "checkbox",
"value": true,
"name": "Required"
},
"MinimumLength": {
"label": "Min. Length",
"type": "hidden",
"value": "",
"name": "MinimumLength"
},
"MaximumLength": {
"label": "Max. Length",
"type": "hidden",
"value": "40",
"name": "MaximumLength"
},
"Predefined": {
"label": "Predefined",
"type": "hidden",
"value": "true",
"name": "Predefined"
},
"ColumnWidth": {
"label": "Column Width",
"type": "select",
"value": [
{
"value": "2",
"selected": false,
"label": "2"
},
{
"value": "3",
"selected": true,
"label": "3"
},
{
"value": "4",
"selected": false,
"label": "4"
},
{
"value": "5",
"selected": false,
"label": "5"
},
{
"value": "6",
"selected": false,
"label": "6"
}
],
"name": "ColumnWidth"
}
},
"fresh": true
}
]<FormComponent onSubmit={handleSubmit(onSubmit)}>
{createdFields.map(
({
Component,
data,
id,
props,
validations,
...rest
}: CFReturnType) => {
return (
<FieldWrapper columns={props?.columns} key={id}>
<Component
register={register({
pattern: regexPattern(validations),
required: isRequired(data),
validate: {
match: (value: string) =>
matchingEmails(
name.toLowerCase(),
value,
getValues(["email", "emailconf"])
),
},
})}
{...{ data, errors, name, props, ...rest }}
/>
</FieldWrapper>
);
}
)}
<Button type="submit" variant="primary">
submit
</Button>
</FormComponent>Partial<Type>enum GlobalConfigKey {
ApigeeServiceHost,
ApigeeServiceHostCC,
ApiHost,
AppInsightsKey,
SITECORE_API_KEY,
GoogleTagManagerId,
}
type GlobalConfig = {
[key in keyof typeof GlobalConfigKey]?: string;
};
interface Window {
globalConfig: GlobalConfig;
angular?: any;
}
declare let globalConfig: GlobalConfig;
declare namespace JSS {
import("@sitecore-jss/sitecore-jss-react");
import { Text } from "@sitecore-jss/sitecore-jss-react";
type Field<
Component extends (...args: any) => any,
Key extends Parameters<Component>[0] = "field"
> = Pick<Parameters<Component>[0], Key>[Key];
export type LinkField = {
value: {
[K in
| "href"
| "id"
| "querystring"
| "text"
| "title"
| "target"
| "class"
| "url"
| "linktype"]?: string;
};
editable?: string;
editableFirstPart?: string;
editableLastPart?: string;
};
type ImageField = {
value?: {
[K in "alt" | "height" | "src" |
};
editable?: string;
};
type TextField = Field<typeof Text>;
export type { LinkField, ImageField, TextField };
}tsinterface Todo { title: string; description: string;}function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) { return { ...todo, ...fieldsToUpdate };}
const todo1 = { title: "organize desk", description: "clear clutter",};
const todo2 = updateTodo(todo1, { description: "throw out trash",});Trytsinterface Props { a?: number; b?: string;}
const obj: Props = { a: 5 };
const obj2: Required<Props> = { a: 5 };Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.2741Property 'b' is missing in type '{ a: number; }' but required in type 'Required<Props>'.Trytsinterface Todo { title: string;}
const todo: Readonly<Todo> = { title: "Delete inactive users",};todo.title = "Hello";Cannot assign to 'title' because it is a read-only property.2540Cannot assign to 'title' because it is a read-only property.Trytsfunction freeze<Type>(obj: Type): Readonly<Type>;tsinterface CatInfo { age: number; breed: string;}type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = { miffy: { age: 10, breed: "Persian" }, boris: { age: 5, breed: "Maine Coon" }, mordred: { age: 16, breed: "British Shorthair" },};cats.boris;
const cats: Record<CatName, CatInfo>Trytsinterface Todo { title: string; description: string; completed: boolean;}type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = { title: "Clean room", completed: false,};todo;
const todo: TodoPreviewTrytsinterface Todo { title: string; description: string; completed: boolean; createdAt: number;}type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = { title: "Clean room", completed: false, createdAt: 1615544252770,};todo;
const todo: TodoPreviewtype TodoInfo = Omit<Todo, "completed" | "createdAt">;
const todoInfo: TodoInfo = { title: "Pick up kids", description: "Kindergarten closes at 5pm",};todoInfo;
const todoInfo: TodoInfoTrytstype T0 = Exclude<"a" | "b" | "c", "a">; type T0 = "b" | "c"type T1 = Exclude<"a" | "b" | "c", "a" | "b">; type T1 = "c"type T2 = Exclude<string | number | (() => void), Function>; type T2 = string | numberTrytstype T0 = Extract<"a" | "b" | "c", "a" | "f">; type T0 = "a"type T1 = Extract<string | number | (() => void), Function>; type T1 = () => voidTrytstype T0 = NonNullable<string | number | undefined>; type T0 = string | numbertype T1 = NonNullable<string[] | null | undefined>; type T1 = string[]Trytsdeclare function f1(arg: { a: number; b: string }): void;type T0 = Parameters<() => string>; type T0 = []type T1 = Parameters<(s: string) => void>; type T1 = [s: string]type T2 = Parameters<<T>(arg: T) => T>; type T2 = [arg: unknown]type T3 = Parameters<typeof f1>; type T3 = [arg: {
a: number;
b: string;
}]type T4 = Parameters<any>; type T4 = unknown[]type T5 = Parameters<never>; type T5 = nevertype T6 = Parameters<string>;Type 'string' does not satisfy the
constraint '(...args: any) => any'.2344Type 'string' does not satisfy the
constraint '(...args: any) => any'. type T6 = nevertype T7 = Parameters<Function>;Type 'Function' does not satisfy the
constraint '(...args: any) => any'.
Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the
constraint '(...args: any) => any'.
Type 'Function' provides no match for the signature '(...args: any): any'. type T7 = neverTrytstype T0 =
constructorParameters<Error
constructor>; type T0 = [message?: string]type T1 =
constructorParameters<Function
constructor>; type T1 = string[]type T2 =
constructorParameters<RegExp
constructor>; type T2 = [pattern: string | RegExp, flags?: string]type T3 =
constructorParameters<any>; type T3 = unknown[]type T4 =
constructorParameters<Function>;Type 'Function' does not satisfy the
constraint 'abstract new (...args: any) => any'.
Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the
constraint 'abstract new (...args: any) => any'.
tsdeclare function f1(): { a: number; b: string };type T0 = ReturnType<() => string>; type T0 = stringtype T1 = ReturnType<(s: string) => void>; type T1 = voidtype T2 = ReturnType<<T>() => T>; type T2 = unknowntype T3 = ReturnType<<T extends U, U extends number[]>() => T>; type T3 = number[]type T4 = ReturnType<typeof f1>; type T4 = {
a: number;
b: string;
}type T5 = ReturnType<any>; type T5 = anytype T6 = ReturnType<never>; type T6 = nevertype T7 = ReturnType<string>;Type 'string' does not satisfy the
constraint '(...args: any) => any'.2344Type 'string' does not satisfy the
constraint '(...args: any) => any'. type T7 = anytype T8 = ReturnType<Function>;Type 'Function' does not satisfy the
constraint '(...args: any) => any'.
Type 'Function' provides no match for the signature '(...args: any): any'.2344Type 'Function' does not satisfy the
constraint '(...args: any) => any'.
Type 'Function' provides no match for the signature '(...args: any): any'. type T8 = anyTrytsclass C { x = 0; y = 0;}type T0 = InstanceType<typeof C>; type T0 = Ctype T1 = InstanceType<any>; type T1 = anytype T2 = InstanceType<never>; type T2 = nevertype T3 = InstanceType<string>;Type 'string' does not satisfy the
constraint 'abstract new (...args: any) => any'.2344Type 'string' does not satisfy the
constraint 'abstract new (...args: any) => any'. type T3 = anytype T4 = InstanceType<Function>;Type 'Function' does not satisfy the
constraint 'abstract new (...args: any) => any'.
Type 'Function' provides no match for the signature 'new (...args: any): any'.2344Type 'Function' does not satisfy the
constraint 'abstract new (...args: any) => any'.
Type 'Function' provides no match for the signature 'new (...args: any): any'. type T4 = anyTrytsfunction toHex(this: Number) { return this.toString(16);}function numberToString(n: ThisParameterType<typeof toHex>) { return toHex.apply(n);}Trytsfunction toHex(this: Number) { return this.toString(16);}
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);console.log(fiveToHex());Trytstype ObjectDescriptor<D, M> = { data?: D; methods?: M & ThisType<D & M>;
// Type of 'this' in methods is D & M};function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M { let data: object = desc.data || {}; let methods: object = desc.methods || {}; return { ...data, ...methods } as D & M;}let obj = makeObject({ data: { x: 0, y: 0 }, methods: { moveBy(dx: number, dy: number) { this.x += dx;
// Strongly typed this this.y += dy;
// Strongly typed this }, },});obj.x = 10;obj.y = 20;obj.moveBy(5, 5);TryPick<ComponentTypes, "text">;
// only use 'text' typePartial<Pick<ComponentTypes, "text">>;
// only use 'text' type
// the text type is optionalRequired<Pick<ComponentTypes, "text">>;
// only use 'text' type
// the text type is required{['class', 'enum', 'interface', 'namespace', 'type', 'variable-and-function'].map(item => (
{item.split('-').join(' ')}
))}class foo {}class Foo {}class Foo {
Bar: number;
BazQux() {}
}class Foo {
bar: number;
bazQux() {}
}enum backgroundColor {}enum BackgroundColor {}interface checkboxProps {}interface CheckboxProps {}interface CheckboxProps {
IsSelected: boolean;
}interface CheckboxProps = {
isSelected: boolean;
}namespace foo {}namespace Foo {}type imageProps = { src: string; alt: string };type ImageProps = { src: string; alt: string };const FooBar = "baz";
const FooBar = () => "baz";const fooBar = "baz";
const fooBar = () => "baz";