let a1 = {
channelID: {
RegExp: ["\\d+", true],
description: "d1"
},
content: {
RegExp: [".+", true],
description: "d2"
}
};
type T1 = {[K in keyof typeof a1]: string}
type Args = {
[key: string]: {
RegExp: [string, boolean],
description: string
}
}
function createArgs<T extends Args>(args: T): T {
return args;
}
type TStringKeys<T extends Args> = {[K in keyof T]: string};
let a1 = createArgs({
channelID: {
RegExp: ["\\d+", true],
description: "d1"
},
content: {
RegExp: [".+", true],
description: "d2"
}
});
type T1 = TStringKeys<typeof a1>
К сожалению на текущий момент(ts4.2.3) избавиться от функции-обёртки не получится. interface IOrder {
date: string,
docTypesName: string,
docId: number,
image: string,
name: string,
price: number,
quantity: number,
removed: number,
}
interface IProduct {
image: string,
name: string,
price: number,
quantity: number,
}
interface IDocument {
date: string,
docId: number,
docTypesName: string,
products: IProduct[],
}
interface IElement {
date: string,
documents: IDocument[]
}
interface IElementMap {
date: string,
documents: Record<string, IDocument>
}
type IResultMap = Record<string, IElementMap>;
function f(orders: IOrder[]): IElement[] {
const result = orders.reduce((accumulator, currentValue) => {
const date = currentValue.date.split(' ')[0];
if (!accumulator[date]) {
accumulator[date] = {
date,
documents: {},
}
}
if (!accumulator[date].documents[currentValue.docTypesName]) {
accumulator[date].documents[currentValue.docTypesName] = {
date: currentValue.date,
docId: currentValue.docId,
docTypesName: currentValue.docTypesName,
products: [],
}
}
accumulator[date].documents[currentValue.docTypesName].products.push({
name: currentValue.name,
price: currentValue.price,
image: currentValue.image,
quantity: currentValue.quantity,
})
return accumulator;
}, {} as IResultMap)
console.log('result', result);
return Object.values(result).map(currentValue => {
console.log('currentValue', currentValue);
return {
...currentValue,
documents: Object.values(currentValue.documents)
}
});
}
console.log(f(orders));
class Foo {
a!: number;
b!: number;
}
function bar(arg:Foo) {};
const randomObj = {a:1, b:2, c:5};
bar(randomObj); // ok
match
может вернуть null
и тогда произойдёт ошибка во время исполнения.const [a, b, c, d, f, g= ''] = value.match(/\d+/g) || [];
Либо, если ты на 146% уверен, что match
обязательно что-нибудь найдёт: const [a, b, c, d, f, g= ''] = value.match(/\d+/g) as string[];
Иначе зачем вообще нужны алиасы в ts?
paths
запилили, чтобы отразить поведение модных сборщиков, типа webpack, а не наоборот. Т.е. предполагается, что paths
используются только когда уже есть сборщик который осуществляет всю логику, а не как первичный источник конфигурации. class A {
static bool: boolean = true;
}
class B extends A {
static readonly bool = true;
}
class C extends A {
static readonly bool = false;
}
function func<T extends typeof A, P = T['bool'] extends true ? number : string>(param: P) { }
func<typeof B>(123); //ok
func<typeof B>('random string'); //not ok
func<typeof C>(123); //not ok
func<typeof C>('random string'); //ok
const elementDefaults = {
'welcome': {
placeholder: 'Type welcome message...',
question: '',
isDescription: false,
description: '',
startButtonText: 'Start',
},
'checkbox': {
placeholder: 'Type question or statement...',
question: '',
isDescription: false,
description: '',
options: [] as string[],
multiple: false,
},
'dropdown': {
placeholder: 'Type question here...',
question: '',
isDescription: false,
description: '',
options: [] as string[],
},
'rating': {
placeholder: 'Type question...',
question: '',
isDescription: false,
description: '',
steps: 10,
defaultRate: 0,
shape: 'stars',
},
'text': {
placeholder: 'Type question...',
question: '',
isDescription: false,
description: '',
maxLength: 99999,
},
'slider': {
placeholder: 'Type question...',
question: '',
isDescription: false,
description: '',
steps: 10,
},
'thanks': {
placeholder: 'Type message...',
question: '',
isDescription: false,
description: '',
}
}
export function getElementSettings<E extends keyof typeof elementTypes>(type: E) {
if(!(type in elementDefaults)) throw new Error("element type doesn't match!");
return elementDefaults[type];
}
type ElementSetting = {
placeholder: string;
question: string;
isDescription: boolean;
description: string;
}
type ElementSettings = {
welcome: ElementSetting & {
startButtonText: string;
},
checkbox: ElementSetting & {
options: string[];
multiple: boolean;
},
dropdown: ElementSetting & {
options: string[];
},
rating: ElementSetting & {
steps: number;
defaultRate: number;
shape: string;
},
text: ElementSetting & {
maxLength: number;
},
slider: ElementSetting & {
steps: number;
},
thanks: ElementSetting
}
const elementDefaults: ElementSettings = {
'welcome': {
placeholder: 'Type welcome message...',
question: '',
isDescription: false,
description: '',
startButtonText: 'Start',
},
'checkbox': {
placeholder: 'Type question or statement...',
question: '',
isDescription: false,
description: '',
options: [],
multiple: false,
},
'dropdown': {
placeholder: 'Type question here...',
question: '',
isDescription: false,
description: '',
options: [],
},
'rating': {
placeholder: 'Type question...',
question: '',
isDescription: false,
description: '',
steps: 10,
defaultRate: 0,
shape: 'stars',
},
'text': {
placeholder: 'Type question...',
question: '',
isDescription: false,
description: '',
maxLength: 99999,
},
'slider': {
placeholder: 'Type question...',
question: '',
isDescription: false,
description: '',
steps: 10,
},
'thanks': {
placeholder: 'Type message...',
question: '',
isDescription: false,
description: '',
}
}
export function getElementSettings<E extends keyof ElementSettings>(type: E): ElementSettings[E] {
if(!(type in elementDefaults)) throw new Error("element type doesn't match!");
return elementDefaults[type];
}